├── .editorconfig ├── .eslintignore ├── .eslintrc.json ├── .github └── FUNDING.yml ├── .gitignore ├── JavaScript ├── 1-Chunk │ ├── 1-initial.js │ ├── 2-prompt-1-gpt-35.js │ ├── 3-prompt-1-gpt-40.js │ ├── 4-prompt-2-gpt-35.js │ ├── 5-prompt-2-gpt-40.js │ ├── 6-prompt-3-gpt-35.js │ ├── 7-prompt-3-gpt-40.js │ └── 8-manually.js ├── 2-Promise │ ├── 1-initial.js │ ├── 2-manual.js │ ├── 3-manual.js │ ├── 4-manual.js │ ├── 5-gpt.js │ ├── 6-gpt.js │ ├── 7-gpt.js │ ├── 8-gpt.js │ ├── 9-gpt.js │ ├── a-gpt.js │ └── config.json ├── 3-Prefetcher │ ├── 1-initial.js │ ├── 2-manual.js │ ├── 3-gpt.js │ ├── 4-gpt.js │ ├── 5-gpt.js │ ├── 6-gpt.js │ ├── 7-gpt.js │ └── 8-gpt.js ├── 4-Options │ ├── 1-initial.js │ └── 2-gpt-4o.js ├── 5-Await-Array │ ├── 1-initial.js │ └── 2-gpt-4o.js └── 6-Await-null │ ├── 1-initial.js │ ├── 2-expected.js │ └── 3-gpt-4o.js ├── LICENSE └── README.md /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | end_of_line = lf 6 | charset = utf-8 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | 10 | [{*.js,*.mjs,*.ts,*.json,*.yml}] 11 | indent_size = 2 12 | indent_style = space 13 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es6": true, 5 | "node": true 6 | }, 7 | "extends": "eslint:recommended", 8 | "parserOptions": { 9 | "ecmaVersion": "latest" 10 | }, 11 | "globals": { 12 | "BigInt": true 13 | }, 14 | "rules": { 15 | "indent": [ 16 | "error", 17 | 2 18 | ], 19 | "linebreak-style": [ 20 | "error", 21 | "unix" 22 | ], 23 | "quotes": [ 24 | "error", 25 | "single" 26 | ], 27 | "semi": [ 28 | "error", 29 | "always" 30 | ], 31 | "no-loop-func": [ 32 | "error" 33 | ], 34 | "block-spacing": [ 35 | "error", 36 | "always" 37 | ], 38 | "camelcase": [ 39 | "error" 40 | ], 41 | "eqeqeq": [ 42 | "error", 43 | "always" 44 | ], 45 | "strict": [ 46 | "error", 47 | "global" 48 | ], 49 | "brace-style": [ 50 | "error", 51 | "1tbs", 52 | { 53 | "allowSingleLine": true 54 | } 55 | ], 56 | "comma-style": [ 57 | "error", 58 | "last" 59 | ], 60 | "comma-spacing": [ 61 | "error", 62 | { 63 | "before": false, 64 | "after": true 65 | } 66 | ], 67 | "eol-last": [ 68 | "error" 69 | ], 70 | "func-call-spacing": [ 71 | "error", 72 | "never" 73 | ], 74 | "key-spacing": [ 75 | "error", 76 | { 77 | "beforeColon": false, 78 | "afterColon": true, 79 | "mode": "minimum" 80 | } 81 | ], 82 | "keyword-spacing": [ 83 | "error", 84 | { 85 | "before": true, 86 | "after": true, 87 | "overrides": { 88 | "function": { 89 | "after": false 90 | } 91 | } 92 | } 93 | ], 94 | "max-len": [ 95 | "error", 96 | { 97 | "code": 80, 98 | "ignoreUrls": true 99 | } 100 | ], 101 | "max-nested-callbacks": [ 102 | "error", 103 | { 104 | "max": 7 105 | } 106 | ], 107 | "new-cap": [ 108 | "error", 109 | { 110 | "newIsCap": true, 111 | "capIsNew": false, 112 | "properties": true 113 | } 114 | ], 115 | "new-parens": [ 116 | "error" 117 | ], 118 | "no-lonely-if": [ 119 | "error" 120 | ], 121 | "no-trailing-spaces": [ 122 | "error" 123 | ], 124 | "no-unneeded-ternary": [ 125 | "error" 126 | ], 127 | "no-whitespace-before-property": [ 128 | "error" 129 | ], 130 | "object-curly-spacing": [ 131 | "error", 132 | "always" 133 | ], 134 | "operator-assignment": [ 135 | "error", 136 | "always" 137 | ], 138 | "operator-linebreak": [ 139 | "error", 140 | "after" 141 | ], 142 | "semi-spacing": [ 143 | "error", 144 | { 145 | "before": false, 146 | "after": true 147 | } 148 | ], 149 | "space-before-blocks": [ 150 | "error", 151 | "always" 152 | ], 153 | "space-before-function-paren": [ 154 | "error", 155 | { 156 | "anonymous": "never", 157 | "named": "never", 158 | "asyncArrow": "always" 159 | } 160 | ], 161 | "space-in-parens": [ 162 | "error", 163 | "never" 164 | ], 165 | "space-infix-ops": [ 166 | "error" 167 | ], 168 | "space-unary-ops": [ 169 | "error", 170 | { 171 | "words": true, 172 | "nonwords": false, 173 | "overrides": { 174 | "typeof": false 175 | } 176 | } 177 | ], 178 | "no-unreachable": [ 179 | "error" 180 | ], 181 | "no-global-assign": [ 182 | "error" 183 | ], 184 | "no-self-compare": [ 185 | "error" 186 | ], 187 | "no-unmodified-loop-condition": [ 188 | "error" 189 | ], 190 | "no-constant-condition": [ 191 | "error", 192 | { 193 | "checkLoops": false 194 | } 195 | ], 196 | "no-console": [ 197 | "off" 198 | ], 199 | "no-useless-concat": [ 200 | "error" 201 | ], 202 | "no-useless-escape": [ 203 | "error" 204 | ], 205 | "no-shadow-restricted-names": [ 206 | "error" 207 | ], 208 | "no-use-before-define": [ 209 | "error", 210 | { 211 | "functions": false 212 | } 213 | ], 214 | "arrow-parens": [ 215 | "error", 216 | "always" 217 | ], 218 | "arrow-body-style": [ 219 | "error", 220 | "as-needed" 221 | ], 222 | "arrow-spacing": [ 223 | "error" 224 | ], 225 | "no-confusing-arrow": [ 226 | "error", 227 | { 228 | "allowParens": true 229 | } 230 | ], 231 | "no-useless-computed-key": [ 232 | "error" 233 | ], 234 | "no-useless-rename": [ 235 | "error" 236 | ], 237 | "no-var": [ 238 | "error" 239 | ], 240 | "object-shorthand": [ 241 | "error", 242 | "always" 243 | ], 244 | "prefer-arrow-callback": [ 245 | "error" 246 | ], 247 | "prefer-const": [ 248 | "error" 249 | ], 250 | "prefer-numeric-literals": [ 251 | "error" 252 | ], 253 | "prefer-rest-params": [ 254 | "error" 255 | ], 256 | "prefer-spread": [ 257 | "error" 258 | ], 259 | "rest-spread-spacing": [ 260 | "error", 261 | "never" 262 | ], 263 | "template-curly-spacing": [ 264 | "error", 265 | "never" 266 | ] 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | patreon: tshemsedinov 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.log 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/1-initial.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Initial code (before optimizations) 4 | 5 | const ID_LENGTH = 4; 6 | 7 | const createIdBuffer = (id) => { 8 | const buffer = new ArrayBuffer(ID_LENGTH); 9 | const view = new DataView(buffer); 10 | view.setInt32(0, id); 11 | return buffer; 12 | }; 13 | 14 | const getStreamId = (buffer) => { 15 | const view = new DataView(buffer); 16 | return view.getInt32(0); 17 | }; 18 | 19 | class Chunk { 20 | static encode(id, payload) { 21 | const idView = new Uint8Array(createIdBuffer(id)); 22 | const chunkView = new Uint8Array(ID_LENGTH + payload.length); 23 | chunkView.set(idView); 24 | chunkView.set(payload, ID_LENGTH); 25 | return chunkView; 26 | } 27 | 28 | static decode(chunkView) { 29 | const id = getStreamId(chunkView.buffer); 30 | const payload = chunkView.subarray(ID_LENGTH); 31 | return { id, payload }; 32 | } 33 | } 34 | 35 | // Usage 36 | 37 | const encoder = new TextEncoder(); 38 | const data = encoder.encode('Hello World'); 39 | const packet = Chunk.encode(123, data); 40 | console.log(packet); 41 | 42 | const { id, payload } = Chunk.decode(packet); 43 | const decoder = new TextDecoder(); 44 | const text = decoder.decode(payload); 45 | console.log({ id, payload: text }); 46 | 47 | const assert = require('node:assert/strict'); 48 | assert.equal(id, 123); 49 | assert.equal(text, 'Hello World'); 50 | 51 | module.exports = { Chunk }; 52 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/2-prompt-1-gpt-35.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Prompt: 4 | // Optimize following code for complexity, readability, memory, and speed 5 | 6 | // ChatGPT 3.5 reply: 7 | // The code looks reasonably efficient, readable, and concise. However, there 8 | // are a few minor optimizations that can be made: 9 | // - Use a constant instead of ID_LENGTH in Chunk.encode(). 10 | // This will make the code more readable and slightly faster since 11 | // the interpreter doesn't have to look up the constant. 12 | // - Use DataView's byteLength property instead of payload.length to calculate 13 | // the length of the chunkView. This avoids having to pass ID_LENGTH around 14 | // and makes the code more concise. 15 | // - Use Int32Array instead of DataView in createIdBuffer() and getStreamId(). 16 | // This will make the code faster since Int32Array is optimized for 32-bit 17 | // integer operations. 18 | 19 | const ID_BYTE_LENGTH = 4; 20 | 21 | const createIdBuffer = (id) => { 22 | const buffer = new ArrayBuffer(ID_BYTE_LENGTH); 23 | const view = new Int32Array(buffer); 24 | view[0] = id; 25 | return buffer; 26 | }; 27 | 28 | const getStreamId = (buffer) => { 29 | const view = new Int32Array(buffer); 30 | return view[0]; 31 | }; 32 | 33 | class Chunk { 34 | static encode(id, payload) { 35 | const idView = new Uint8Array(createIdBuffer(id)); 36 | const chunkView = new Uint8Array(idView.byteLength + payload.byteLength); 37 | chunkView.set(idView); 38 | chunkView.set(payload, idView.byteLength); 39 | return chunkView; 40 | } 41 | 42 | static decode(chunkView) { 43 | const id = getStreamId(chunkView.buffer); 44 | const payload = chunkView.subarray(ID_BYTE_LENGTH); 45 | return { id, payload }; 46 | } 47 | } 48 | 49 | // Usage example 50 | 51 | const encoder = new TextEncoder(); 52 | const data = encoder.encode('Hello World'); 53 | const packet = Chunk.encode(123, data); 54 | console.log(packet); 55 | 56 | const { id, payload } = Chunk.decode(packet); 57 | const decoder = new TextDecoder(); 58 | const text = decoder.decode(payload); 59 | console.log({ id, payload: text }); 60 | 61 | const assert = require('node:assert/strict'); 62 | assert.equal(id, 123); 63 | assert.equal(text, 'Hello World'); 64 | 65 | module.exports = { Chunk }; 66 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/3-prompt-1-gpt-40.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Prompt: 4 | // Optimize following code for complexity, readability, memory, and speed 5 | 6 | // ChatGPT 4 reply: 7 | // The code is already quite efficient, but there are a few changes 8 | // that can be made to improve readability, complexity, and memory. 9 | // 10 | // Optimizations made: 11 | // - Moved createIdBuffer and getStreamId functions as static methods 12 | // inside the Chunk class. This improves readability by grouping related 13 | // functionality together and reduces complexity by eliminating 14 | // the need for separate functions. 15 | // - Removed the idView variable in encode method by directly creating 16 | // the buffer and then creating the Uint8Array. This reduces memory 17 | // overhead by eliminating the need for an intermediate variable. 18 | // 19 | // The optimizations made have a minimal impact on speed, 20 | // but they do help with readability, complexity, and memory. 21 | // 22 | // Here's the optimized version: 23 | 24 | const ID_LENGTH = 4; 25 | 26 | class Chunk { 27 | static createIdBuffer(id) { 28 | const buffer = new ArrayBuffer(ID_LENGTH); 29 | const view = new DataView(buffer); 30 | view.setInt32(0, id); 31 | return buffer; 32 | } 33 | 34 | static getStreamId(buffer) { 35 | const view = new DataView(buffer); 36 | return view.getInt32(0); 37 | } 38 | 39 | static encode(id, payload) { 40 | const idBuffer = Chunk.createIdBuffer(id); 41 | const idView = new Uint8Array(idBuffer); 42 | const chunkView = new Uint8Array(ID_LENGTH + payload.length); 43 | chunkView.set(idView); 44 | chunkView.set(payload, ID_LENGTH); 45 | return chunkView; 46 | } 47 | 48 | static decode(chunkView) { 49 | const id = Chunk.getStreamId(chunkView.buffer); 50 | const payload = chunkView.subarray(ID_LENGTH); 51 | return { id, payload }; 52 | } 53 | } 54 | 55 | // Usage example 56 | 57 | const encoder = new TextEncoder(); 58 | const data = encoder.encode('Hello World'); 59 | const packet = Chunk.encode(123, data); 60 | console.log(packet); 61 | 62 | const { id, payload } = Chunk.decode(packet); 63 | const decoder = new TextDecoder(); 64 | const text = decoder.decode(payload); 65 | console.log({ id, payload: text }); 66 | 67 | const assert = require('node:assert/strict'); 68 | assert.equal(id, 123); 69 | assert.equal(text, 'Hello World'); 70 | 71 | module.exports = { Chunk }; 72 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/4-prompt-2-gpt-35.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Prompt: 4 | // Optimize following code 5 | 6 | // ChatGPT 3.5 reply: 7 | // Here are some optimizations that can be made to the given code: 8 | // - Use a TypedArray instead of DataView: 9 | // Since the DataView is slower than TypedArray, it is better to use 10 | // the TypedArray instead of the DataView. 11 | // - Use Int32Array instead of DataView: 12 | // Since the createIdBuffer function always creates an ArrayBuffer 13 | // of length ID_LENGTH (which is always 4), we can use the Int32Array 14 | // to set the integer value at the beginning of the buffer. 15 | // - Use a shared buffer: 16 | // Instead of creating a new buffer every time createIdBuffer is called, 17 | // we can use a shared buffer and only modify the integer value using 18 | // setInt32. This can save memory allocations and deallocations. 19 | // 20 | // With these optimizations, we are using a shared buffer and a faster 21 | // TypedArray to reduce memory allocations and improve the performance 22 | // of the code. 23 | // 24 | // Here is the optimized code: 25 | 26 | const ID_LENGTH = 4; 27 | const idBuffer = new ArrayBuffer(ID_LENGTH); 28 | const idView = new Int32Array(idBuffer); 29 | 30 | class Chunk { 31 | static encode(id, payload) { 32 | idView[0] = id; 33 | const chunkView = new Uint8Array(idBuffer.byteLength + payload.length); 34 | chunkView.set(new Uint8Array(idBuffer)); 35 | chunkView.set(payload, ID_LENGTH); 36 | return chunkView; 37 | } 38 | 39 | static decode(chunkView) { 40 | const id = new Int32Array(chunkView.buffer, 0, 1)[0]; 41 | const payload = chunkView.subarray(ID_LENGTH); 42 | return { id, payload }; 43 | } 44 | } 45 | 46 | // Usage example 47 | 48 | const encoder = new TextEncoder(); 49 | const data = encoder.encode('Hello World'); 50 | const packet = Chunk.encode(123, data); 51 | console.log(packet); 52 | 53 | const { id, payload } = Chunk.decode(packet); 54 | const decoder = new TextDecoder(); 55 | const text = decoder.decode(payload); 56 | console.log({ id, payload: text }); 57 | 58 | const assert = require('node:assert/strict'); 59 | assert.equal(id, 123); 60 | assert.equal(text, 'Hello World'); 61 | 62 | module.exports = { Chunk }; 63 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/5-prompt-2-gpt-40.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Prompt: 4 | // Optimize following code 5 | 6 | // ChatGPT 4 reply: 7 | // You can optimize the given code by removing the unnecessary createIdBuffer 8 | // function and simplifying the Chunk.encode method. 9 | // 10 | // Here's the optimized code: 11 | 12 | const ID_LENGTH = 4; 13 | 14 | const getStreamId = (buffer) => { 15 | const view = new DataView(buffer); 16 | return view.getInt32(0); 17 | }; 18 | 19 | class Chunk { 20 | static encode(id, payload) { 21 | const chunkView = new Uint8Array(ID_LENGTH + payload.length); 22 | const idView = new DataView(chunkView.buffer); 23 | idView.setInt32(0, id); 24 | chunkView.set(payload, ID_LENGTH); 25 | return chunkView; 26 | } 27 | 28 | static decode(chunkView) { 29 | const id = getStreamId(chunkView.buffer); 30 | const payload = chunkView.subarray(ID_LENGTH); 31 | return { id, payload }; 32 | } 33 | } 34 | 35 | // Usage example 36 | 37 | const encoder = new TextEncoder(); 38 | const data = encoder.encode('Hello World'); 39 | const packet = Chunk.encode(123, data); 40 | console.log(packet); 41 | 42 | const { id, payload } = Chunk.decode(packet); 43 | const decoder = new TextDecoder(); 44 | const text = decoder.decode(payload); 45 | console.log({ id, payload: text }); 46 | 47 | const assert = require('node:assert/strict'); 48 | assert.equal(id, 123); 49 | assert.equal(text, 'Hello World'); 50 | 51 | module.exports = { Chunk }; 52 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/6-prompt-3-gpt-35.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Prompt: 4 | // Can you please optimize following code: 5 | // - use one typed array memory allocation instead of two 6 | // - remove unneeded class 7 | // - just two functions 8 | 9 | // ChatGPT 3.5 reply: 10 | // Certainly! 11 | // Changes made: 12 | // - Removed the Chunk class, since it was not needed. 13 | // - Combined the createIdBuffer and encodeChunk functions into 14 | // a single function, encodeChunk. 15 | // - Moved the allocation of the memory for chunkView to 16 | // the encodeChunk function, and created the DataView object 17 | // using the buffer of chunkView. 18 | // - Combined the getStreamId and decodeChunk functions into 19 | // a single function, decodeChunk. 20 | // - Removed the need for the idView variable in encodeChunk 21 | // by setting the ID directly on the DataView object. 22 | // 23 | // This code now uses only one typed array memory allocation instead of two, 24 | // and has been simplified to just two functions. 25 | // 26 | // Here's the optimized code: 27 | 28 | const ID_LENGTH = 4; 29 | 30 | const encodeChunk = (id, payload) => { 31 | const chunkView = new Uint8Array(ID_LENGTH + payload.length); 32 | const view = new DataView(chunkView.buffer); 33 | view.setInt32(0, id); 34 | chunkView.set(payload, ID_LENGTH); 35 | return chunkView; 36 | }; 37 | 38 | const decodeChunk = (chunkView) => { 39 | const view = new DataView(chunkView.buffer); 40 | const id = view.getInt32(0); 41 | const payload = chunkView.subarray(ID_LENGTH); 42 | return { id, payload }; 43 | }; 44 | 45 | // Usage example 46 | 47 | const encoder = new TextEncoder(); 48 | const data = encoder.encode('Hello World'); 49 | const packet = encodeChunk(123, data); 50 | console.log(packet); 51 | 52 | const { id, payload } = decodeChunk(packet); 53 | const decoder = new TextDecoder(); 54 | const text = decoder.decode(payload); 55 | console.log({ id, payload: text }); 56 | 57 | const assert = require('node:assert/strict'); 58 | assert.equal(id, 123); 59 | assert.equal(text, 'Hello World'); 60 | 61 | module.exports = { encodeChunk, decodeChunk }; 62 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/7-prompt-3-gpt-40.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Prompt: 4 | // Can you please optimize following code: 5 | // - use one typed array memory allocation instead of two 6 | // - remove unneeded class 7 | // - just two functions 8 | 9 | // ChatGPT 4 reply: 10 | // I removed the Chunk class and the createIdBuffer function, and directly 11 | // used a single typed array allocation (chunkView) in both encodeChunk and 12 | // decodeChunk functions. The getStreamId function was also removed and its 13 | // functionality was integrated into the decodeChunk function. 14 | // Here's the optimized code with a single typed array allocation and 15 | // just two functions: 16 | 17 | const ID_LENGTH = 4; 18 | 19 | const encodeChunk = (id, payload) => { 20 | const chunkView = new Uint8Array(ID_LENGTH + payload.length); 21 | const view = new DataView(chunkView.buffer); 22 | view.setInt32(0, id); 23 | chunkView.set(payload, ID_LENGTH); 24 | return chunkView; 25 | }; 26 | 27 | const decodeChunk = (chunkView) => { 28 | const view = new DataView(chunkView.buffer); 29 | const id = view.getInt32(0); 30 | const payload = chunkView.subarray(ID_LENGTH); 31 | return { id, payload }; 32 | }; 33 | 34 | // Usage example 35 | 36 | const encoder = new TextEncoder(); 37 | const data = encoder.encode('Hello World'); 38 | const packet = encodeChunk(123, data); 39 | console.log(packet); 40 | 41 | const { id, payload } = decodeChunk(packet); 42 | const decoder = new TextDecoder(); 43 | const text = decoder.decode(payload); 44 | console.log({ id, payload: text }); 45 | 46 | const assert = require('node:assert/strict'); 47 | assert.equal(id, 123); 48 | assert.equal(text, 'Hello World'); 49 | 50 | module.exports = { encodeChunk, decodeChunk }; 51 | -------------------------------------------------------------------------------- /JavaScript/1-Chunk/8-manually.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const ID_LENGTH = 4; 4 | 5 | const encodeChunk = (id, payload) => { 6 | const chunkView = new Uint8Array(ID_LENGTH + payload.length); 7 | const view = new DataView(chunkView.buffer); 8 | view.setInt32(0, id); 9 | chunkView.set(payload, ID_LENGTH); 10 | return chunkView; 11 | }; 12 | 13 | const decodeChunk = (chunkView) => { 14 | const view = new DataView(chunkView.buffer); 15 | const id = view.getInt32(0); 16 | const payload = chunkView.subarray(ID_LENGTH); 17 | return { id, payload }; 18 | }; 19 | 20 | // Usage example 21 | 22 | const encoder = new TextEncoder(); 23 | const data = encoder.encode('Hello World'); 24 | const packet = encodeChunk(123, data); 25 | console.log(packet); 26 | 27 | const { id, payload } = decodeChunk(packet); 28 | const decoder = new TextDecoder(); 29 | const text = decoder.decode(payload); 30 | console.log({ id, payload: text }); 31 | 32 | const assert = require('node:assert/strict'); 33 | assert.equal(id, 123); 34 | assert.equal(text, 'Hello World'); 35 | 36 | module.exports = { encodeChunk, decodeChunk }; 37 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/1-initial.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Initial code (before optimizations) 4 | 5 | const fs = require('node:fs').promises; 6 | 7 | (async () => { 8 | let data; 9 | try { 10 | data = await fs.readFile('config.json', 'utf8'); 11 | } catch {} 12 | const config = data ? JSON.parse(data) : { port: 80 }; 13 | console.log({ config }); 14 | })(); 15 | 16 | // Problems: 17 | // - mutable data 18 | // - empty catch 19 | // - default config placed in one line with parsing 20 | // - ternary operator reduces readability in this place 21 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/2-manual.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Manual optimizations 4 | 5 | const fs = require('node:fs').promises; 6 | 7 | (async () => { 8 | let config; 9 | try { 10 | const data = await fs.readFile('config.json', 'utf8'); 11 | config = JSON.parse(data); 12 | } catch { 13 | config = { port: 80 }; 14 | } 15 | console.log({ config }); 16 | })(); 17 | 18 | // Problems: 19 | // - mutable config variable 20 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/3-manual.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Manual optimizations 4 | 5 | const fs = require('node:fs').promises; 6 | 7 | (async () => { 8 | let config; 9 | await fs 10 | .readFile('config.json', 'utf8') 11 | .then((data) => { 12 | config = JSON.parse(data); 13 | }) 14 | .catch(() => { 15 | config = { port: 80 }; 16 | }); 17 | console.log({ config }); 18 | })(); 19 | 20 | // Problems: 21 | // - mutable config variable 22 | // - then/cache write to outer scope 23 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/4-manual.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('node:fs').promises; 4 | 5 | // Manual optimizations 6 | 7 | (async () => { 8 | const config = await fs 9 | .readFile('config.json', 'utf8') 10 | .then(JSON.parse) 11 | .catch(() => ({ port: 80 })); 12 | console.log({ config }); 13 | })(); 14 | 15 | // Final optimizations as for me 16 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/5-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Please optimize following 5 | // Reply: Below is the optimized version of the given code snippet: 6 | 7 | const fs = require('node:fs').promises; 8 | 9 | (async () => { 10 | try { 11 | const data = await fs.readFile('config.json', 'utf8'); 12 | const config = JSON.parse(data); 13 | console.log({ config }); 14 | } catch { 15 | console.log({ config: { port: 80 } }); 16 | } 17 | })(); 18 | 19 | // Chat GPT comments: The optimization includes: 20 | // - Moving the data variable inside the try block to limit its scope. 21 | // - Removing the unnecessary conditional operator in favor of directly logging 22 | // the default configuration object inside the catch block. 23 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/6-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Optimize following without moving console.log inside try block 5 | // Reply: I understand that you want to keep the console.log statement 6 | // outside the try-catch block. Here's an optimized version of the code: 7 | 8 | const fs = require('node:fs').promises; 9 | 10 | (async () => { 11 | let config; 12 | try { 13 | const data = await fs.readFile('config.json', 'utf8'); 14 | config = JSON.parse(data); 15 | } catch { 16 | config = { port: 80 }; 17 | } 18 | console.log({ config }); 19 | })(); 20 | 21 | // Chat GPT comments: 22 | // The optimization includes: 23 | // - Moving the config variable outside the try-catch block 24 | // to maintain its scope. 25 | // - Removing the unnecessary conditional operator in favor 26 | // of directly assigning the parsed JSON or default configuration 27 | // object inside the try-catch block. 28 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/7-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Optimize without moving console.log inside try block and without let 5 | // (use just const) 6 | // Reply: Understood. Here's an optimized version of the code without 7 | // using let and keeping console.log outside the try-catch block: 8 | 9 | const fs = require('node:fs').promises; 10 | 11 | (async () => { 12 | const config = await (async () => { 13 | try { 14 | const data = await fs.readFile('config.json', 'utf8'); 15 | return JSON.parse(data); 16 | } catch { 17 | return { port: 80 }; 18 | } 19 | })(); 20 | 21 | console.log({ config }); 22 | })(); 23 | 24 | // Chat GPT comments: 25 | // This version wraps the try-catch block inside an immediately invoked 26 | // async function expression. This allows you to use const for the config 27 | // variable and maintain the scope of the console.log statement outside 28 | // the try-catch block. 29 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/8-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Optimize without moving console.log inside try block, 5 | // without let (use just const), and without adding extra immediately 6 | // invoked function. 7 | // Reply: As per your request, here's an optimized version of the code 8 | // without using let, moving console.log inside the try-catch block, 9 | // and without adding an extra immediately invoked function: 10 | 11 | const fs = require('node:fs').promises; 12 | 13 | (async () => { 14 | const readConfig = async () => { 15 | try { 16 | const data = await fs.readFile('config.json', 'utf8'); 17 | return JSON.parse(data); 18 | } catch (error) { 19 | return { port: 80 }; 20 | } 21 | }; 22 | 23 | const config = await readConfig(); 24 | console.log({ config }); 25 | })(); 26 | 27 | // Chat GPT comments: 28 | // In this version, we define an async function called readConfig() 29 | // that handles reading and parsing the config file, and returns 30 | // the parsed JSON or the default configuration object if an error occurs. 31 | // Then we await the result of this function and assign it to the config 32 | // constant. The console.log statement remains outside the try-catch block. 33 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/9-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Optimize without moving console.log inside try block, without let 5 | // (use just const), without adding extra immediately invoked function, 6 | // and without even creating new async function 7 | // Reply: I apologize for the confusion. Based on your requirements, it is not 8 | // possible to optimize the code further without moving the console.log inside 9 | // the try-catch block, without using let, and without adding extra functions. 10 | // The original code you provided is already an efficient implementation given 11 | // these constraints: 12 | 13 | const fs = require('node:fs').promises; 14 | 15 | (async () => { 16 | let data; 17 | try { 18 | data = await fs.readFile('config.json', 'utf8'); 19 | } catch {} 20 | const config = data ? JSON.parse(data) : { port: 80 }; 21 | console.log({ config }); 22 | })(); 23 | 24 | // Chat GPT comments: 25 | // In this code, the use of let is necessary because the data variable is 26 | // assigned a value inside the try block, and its value might change depending 27 | // on whether the file read operation is successful or not. The same applies to 28 | // the config variable. The try-catch block and the conditional operator are 29 | // also essential to handle errors and assign a default configuration value 30 | // when needed. 31 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/a-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | 5 | // Prompt: Optimize without moving console.log inside try block, without let 6 | // (use just const), and without adding extra immediately invoked function, 7 | // and without even creating new async function. 8 | // I believe it is possible to rewrite it with all listed requirements. 9 | // Maybe you can use Promise chain for that. 10 | 11 | // Reply: You're right, using a Promise chain can help achieve your 12 | // requirements. Here's the optimized code using a Promise chain: 13 | 14 | const fs = require('node:fs').promises; 15 | 16 | fs.readFile('config.json', 'utf8') 17 | .then(JSON.parse) 18 | .catch(() => ({ port: 80 })) 19 | .then((config) => { 20 | console.log({ config }); 21 | }); 22 | 23 | // Chat GPT comments: 24 | // In this version, we use the Promise returned by fs.readFile and chain 25 | // a then for parsing the JSON. If an error occurs, the catch block is 26 | // executed, which returns the default configuration object. 27 | // Finally, we have a then block to log the config object. 28 | // This approach meets all your requirements: 29 | // - The console.log statement remains outside the try-catch block. 30 | // - We don't use let. 31 | // - No extra immediately invoked functions are added. 32 | // - We don't create a new async function. 33 | 34 | // Timur: What was missing for a solution when you said "it is not possible"? 35 | 36 | // When I initially stated that it was not possible, I was primarily focused 37 | // on optimizing the code within the context of the async-await syntax 38 | // and did not consider switching to a Promise chain as a valid alternative. 39 | // The oversight resulted from my narrow approach to the problem, and I didn't 40 | // think to explore other possibilities such as using a Promise chain. 41 | // Your suggestion to use a Promise chain highlighted a more appropriate 42 | // solution that met all your requirements. It's important to consider different 43 | // approaches when optimizing code to make sure the best solution is found. 44 | 45 | // Timur: The reason for focusing on a single aspect is the saving of 46 | // computing resources, did I understand correctly? 47 | 48 | // The focus on a single aspect was not due to saving computing resources but 49 | // rather a limitation in my thought process at that moment. Your suggestion to 50 | // consider a Promise chain helped broaden the scope and resulted in a more 51 | // suitable solution. 52 | -------------------------------------------------------------------------------- /JavaScript/2-Promise/config.json: -------------------------------------------------------------------------------- 1 | { "port": 8080 } 2 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/1-initial.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Initial code (before optimizations) 4 | 5 | const crypto = require('crypto'); 6 | 7 | class CryptoRandomPrefetcher { 8 | constructor(bufSize, valueSize) { 9 | if (bufSize % valueSize !== 0) { 10 | throw new RangeError('buffer size must be a multiple of value size'); 11 | } 12 | this.buf = crypto.randomBytes(bufSize); 13 | this.pos = 0; 14 | this.vsz = valueSize; 15 | } 16 | 17 | // Return Buffer with next `valueSize` random bytes. 18 | next() { 19 | if (this.pos === this.buf.length) { 20 | this.pos = 0; 21 | crypto.randomFillSync(this.buf); 22 | } 23 | const end = this.pos + this.vsz; 24 | const buf = this.buf.slice(this.pos, end); 25 | this.pos = end; 26 | return buf; 27 | } 28 | 29 | [Symbol.iterator]() { 30 | return { 31 | [Symbol.iterator]() { 32 | return this; 33 | }, 34 | next: () => ({ value: this.next(), done: false }), 35 | }; 36 | } 37 | } 38 | 39 | const cryptoPrefetcher = (bufSize, valueSize) => 40 | new CryptoRandomPrefetcher(bufSize, valueSize); 41 | 42 | const randPrefetcher = cryptoPrefetcher(4096, 4); 43 | const UINT32_MAX = 0xffffffff; 44 | 45 | const cryptoRandom = () => 46 | randPrefetcher.next().readUInt32LE(0, true) / (UINT32_MAX + 1); 47 | 48 | module.exports = { cryptoRandom }; 49 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/2-manual.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const crypto = require('node:crypto'); 4 | 5 | const UINT32_MAX = 0xffffffff; 6 | const BUF_LEN = 1024; 7 | const BUF_SIZE = BUF_LEN * Uint32Array.BYTES_PER_ELEMENT; 8 | 9 | const randomPrefetcher = { 10 | buf: crypto.randomBytes(BUF_SIZE), 11 | pos: 0, 12 | next() { 13 | const { buf, pos } = this; 14 | let start = pos; 15 | if (start === buf.length) { 16 | start = 0; 17 | crypto.randomFillSync(buf); 18 | } 19 | const end = start + Uint32Array.BYTES_PER_ELEMENT; 20 | this.pos = end; 21 | return buf.slice(start, end); 22 | }, 23 | }; 24 | 25 | const cryptoRandom = () => { 26 | const buf = randomPrefetcher.next(); 27 | return buf.readUInt32LE(0) / (UINT32_MAX + 1); 28 | }; 29 | 30 | module.exports = { cryptoRandom }; 31 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/3-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Please optimize following code 5 | // Reply: Here's the optimized version of the given code: 6 | 7 | const crypto = require('crypto'); 8 | 9 | class CryptoRandomPrefetcher { 10 | constructor(bufSize, valueSize) { 11 | if (bufSize % valueSize !== 0) { 12 | throw new RangeError('buffer size must be a multiple of value size'); 13 | } 14 | this.buf = crypto.randomBytes(bufSize); 15 | this.pos = 0; 16 | this.vsz = valueSize; 17 | } 18 | 19 | // Return Buffer with next `valueSize` random bytes. 20 | next() { 21 | if (this.pos === this.buf.length) { 22 | this.pos = 0; 23 | crypto.randomFillSync(this.buf); 24 | } 25 | const end = this.pos + this.vsz; 26 | const buf = this.buf.slice(this.pos, end); 27 | this.pos = end; 28 | return buf; 29 | } 30 | 31 | [Symbol.iterator]() { 32 | const nextFunc = () => ({ value: this.next(), done: false }); 33 | return { 34 | [Symbol.iterator]() { 35 | return this; 36 | }, 37 | next: nextFunc, 38 | }; 39 | } 40 | } 41 | 42 | const cryptoPrefetcher = (bufSize, valueSize) => 43 | new CryptoRandomPrefetcher(bufSize, valueSize); 44 | 45 | const randPrefetcher = cryptoPrefetcher(4096, 4); 46 | const UINT32_MAX = 0xffffffff; 47 | 48 | const cryptoRandom = () => 49 | randPrefetcher.next().readUInt32LE(0) / (UINT32_MAX + 1); 50 | 51 | // Chat GPT comments: 52 | // I have made the following optimization: 53 | // - Removed the second parameter true from the readUInt32LE() function call, 54 | // as it is not needed. By default, it is set to false, which means 55 | // the function will not check for out of bounds access. Since you have 56 | // already ensured that the buffer size is a multiple of the value size, 57 | // this check is not necessary. 58 | 59 | module.exports = { cryptoRandom }; 60 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/4-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: 5 | // - We do not need class here, convert prefetcher to the object with 6 | // methods and properties (state) 7 | // - No need in iterable contract here, prefetcher can have just next() 8 | // function to get next value 9 | // - Use node: prefix in require 10 | // Reply: 11 | // Here's the refactored version of the code with the requested changes: 12 | 13 | const crypto = require('node:crypto'); 14 | 15 | function createCryptoRandomPrefetcher(bufSize, valueSize) { 16 | if (bufSize % valueSize !== 0) { 17 | throw new RangeError('buffer size must be a multiple of value size'); 18 | } 19 | 20 | const state = { 21 | buf: crypto.randomBytes(bufSize), 22 | pos: 0, 23 | vsz: valueSize, 24 | }; 25 | 26 | function next() { 27 | if (state.pos === state.buf.length) { 28 | state.pos = 0; 29 | crypto.randomFillSync(state.buf); 30 | } 31 | const end = state.pos + state.vsz; 32 | const buf = state.buf.slice(state.pos, end); 33 | state.pos = end; 34 | return buf; 35 | } 36 | 37 | return { next }; 38 | } 39 | 40 | const cryptoPrefetcher = (bufSize, valueSize) => 41 | createCryptoRandomPrefetcher(bufSize, valueSize); 42 | 43 | const randPrefetcher = cryptoPrefetcher(4096, 4); 44 | const UINT32_MAX = 0xffffffff; 45 | 46 | const cryptoRandom = () => 47 | randPrefetcher.next().readUInt32LE(0) / (UINT32_MAX + 1); 48 | 49 | module.exports = { cryptoRandom }; 50 | 51 | // Chat GPT comments: 52 | // The changes I made are: 53 | // - Replaced the CryptoRandomPrefetcher class with a factory function 54 | // createCryptoRandomPrefetcher that returns an object with a next method. 55 | // - Removed the iterable implementation from the prefetcher. 56 | // - Changed the require statement to use the node: prefix. 57 | 58 | module.exports = { cryptoRandom }; 59 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/5-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: 5 | // - We do not need factory, just define object and combine state and next() 6 | // function to this single instance 7 | // Reply: 8 | // Here's the code with the requested changes: 9 | 10 | const crypto = require('node:crypto'); 11 | 12 | const bufSize = 4096; 13 | const valueSize = 4; 14 | 15 | if (bufSize % valueSize !== 0) { 16 | throw new RangeError('buffer size must be a multiple of value size'); 17 | } 18 | 19 | const randPrefetcher = { 20 | buf: crypto.randomBytes(bufSize), 21 | pos: 0, 22 | vsz: valueSize, 23 | 24 | next() { 25 | if (this.pos === this.buf.length) { 26 | this.pos = 0; 27 | crypto.randomFillSync(this.buf); 28 | } 29 | const end = this.pos + this.vsz; 30 | const buf = this.buf.slice(this.pos, end); 31 | this.pos = end; 32 | return buf; 33 | }, 34 | }; 35 | 36 | const UINT32_MAX = 0xffffffff; 37 | 38 | const cryptoRandom = () => 39 | randPrefetcher.next().readUInt32LE(0) / (UINT32_MAX + 1); 40 | 41 | // Chat GPT comments: 42 | // In this version of the code: 43 | // - Removed the factory function and directly defined the randPrefetcher 44 | // object with its state and next() method. 45 | // - Removed the cryptoPrefetcher function as it's no longer needed. 46 | 47 | module.exports = { cryptoRandom }; 48 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/6-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Remove dead code 5 | // Reply: 6 | // Here's the cleaned-up version of the code with dead code removed: 7 | 8 | const crypto = require('node:crypto'); 9 | 10 | const bufSize = 4096; 11 | const valueSize = 4; 12 | 13 | if (bufSize % valueSize !== 0) { 14 | throw new RangeError('buffer size must be a multiple of value size'); 15 | } 16 | 17 | const randPrefetcher = { 18 | buf: crypto.randomBytes(bufSize), 19 | pos: 0, 20 | vsz: valueSize, 21 | 22 | next() { 23 | if (this.pos === this.buf.length) { 24 | this.pos = 0; 25 | crypto.randomFillSync(this.buf); 26 | } 27 | const end = this.pos + this.vsz; 28 | const buf = this.buf.slice(this.pos, end); 29 | this.pos = end; 30 | return buf; 31 | }, 32 | }; 33 | 34 | const UINT32_MAX = 0xffffffff; 35 | 36 | const cryptoRandom = () => 37 | randPrefetcher.next().readUInt32LE(0) / (UINT32_MAX + 1); 38 | 39 | module.exports = { cryptoRandom }; 40 | 41 | // Chat GPT comments: 42 | // The previous versions of the code did not contain any dead code. The code 43 | // provided above is already clean and free from dead or unreachable code. 44 | 45 | module.exports = { cryptoRandom }; 46 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/7-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: Remove if statement with throw because it can be precalculated 5 | // Reply: 6 | // You're correct that the check can be precalculated if the bufSize and 7 | // valueSize are constants. 8 | // In that case, the code can be simplified as follows: 9 | 10 | const crypto = require('node:crypto'); 11 | 12 | const bufSize = 4096; 13 | const valueSize = 4; 14 | 15 | const randPrefetcher = { 16 | buf: crypto.randomBytes(bufSize), 17 | pos: 0, 18 | vsz: valueSize, 19 | 20 | next() { 21 | if (this.pos === this.buf.length) { 22 | this.pos = 0; 23 | crypto.randomFillSync(this.buf); 24 | } 25 | const end = this.pos + this.vsz; 26 | const buf = this.buf.slice(this.pos, end); 27 | this.pos = end; 28 | return buf; 29 | }, 30 | }; 31 | 32 | const UINT32_MAX = 0xffffffff; 33 | 34 | const cryptoRandom = () => 35 | randPrefetcher.next().readUInt32LE(0) / (UINT32_MAX + 1); 36 | 37 | // Chat GPT comments: 38 | // I've removed the if statement with the throw since the bufSize and 39 | // valueSize are constants and the condition (bufSize % valueSize !== 0) 40 | // can be precalculated. In this case, it evaluates to false, so there's 41 | // no need for the check in the code. 42 | 43 | module.exports = { cryptoRandom }; 44 | -------------------------------------------------------------------------------- /JavaScript/3-Prefetcher/8-gpt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Chat GPT version 4 4 | // Prompt: 5 | // - We do not need vsz property (copy of valueSize) because it is constant 6 | // - Use UPPER_CAMEL for file-wide constants 7 | // Reply: 8 | // Here's the updated code with the file-wide constants bufSize and valueSize 9 | // using UPPER_CAMEL case: 10 | 11 | const crypto = require('node:crypto'); 12 | 13 | const BUF_SIZE = 4096; 14 | const VALUE_SIZE = 4; 15 | 16 | const randPrefetcher = { 17 | buf: crypto.randomBytes(BUF_SIZE), 18 | pos: 0, 19 | 20 | next() { 21 | if (this.pos === this.buf.length) { 22 | this.pos = 0; 23 | crypto.randomFillSync(this.buf); 24 | } 25 | const end = this.pos + VALUE_SIZE; 26 | const buf = this.buf.slice(this.pos, end); 27 | this.pos = end; 28 | return buf; 29 | }, 30 | }; 31 | 32 | const UINT32_MAX = 0xffffffff; 33 | 34 | const cryptoRandom = () => 35 | randPrefetcher.next().readUInt32LE(0) / (UINT32_MAX + 1); 36 | 37 | // Chat GPT comments: 38 | // I've removed the vsz property from the randPrefetcher object and replaced 39 | // its usage in the next() method with the constant valueSize. 40 | // I've changed the names of the constants bufSize and valueSize to BUF_SIZE and 41 | // VALUE_SIZE, respectively, to follow the UPPER_CAMEL naming convention for 42 | // file-wide constants. 43 | 44 | module.exports = { cryptoRandom }; 45 | -------------------------------------------------------------------------------- /JavaScript/4-Options/1-initial.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Please implement getSelected function and 4 | // propose solution for following example: 5 | 6 | // Place your code here 7 | const options = { 8 | [x]: 'Uno', 9 | [_]: 'Due', 10 | [x]: 'Tre', 11 | [_]: 'Quatro', 12 | }; 13 | const selected = getSelected(options); 14 | console.log(selected); 15 | 16 | // We need following output: ["Uno", "Tre"] 17 | -------------------------------------------------------------------------------- /JavaScript/4-Options/2-gpt-4o.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Prompt: 4 | // Please implement getSelected function and 5 | // propose solution for following example: 6 | 7 | // Place your code here 8 | const options = { 9 | [x]: 'Uno', 10 | [_]: 'Due', 11 | [x]: 'Tre', 12 | [_]: 'Quatro', 13 | }; 14 | const selected = getSelected(options); 15 | console.log(selected); 16 | 17 | // We need following output: ["Uno", "Tre"] 18 | */ 19 | 20 | // Answer: 21 | 22 | const x = Symbol('x'); 23 | const _ = Symbol('_'); 24 | 25 | const options = { 26 | [x]: 'Uno', 27 | [_]: 'Due', 28 | [x]: 'Tre', 29 | [_]: 'Quatro', 30 | }; 31 | 32 | function getSelected(options) { 33 | const selectedKeys = Object.getOwnPropertySymbols(options).filter(symbol => symbol.description === 'x'); 34 | return selectedKeys.map(key => options[key]); 35 | } 36 | 37 | const selected = getSelected(options); 38 | console.log(selected); // Output: ["Uno", "Tre"] 39 | -------------------------------------------------------------------------------- /JavaScript/5-Await-Array/1-initial.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Please propose solution to have behavior like 4 | // Promise.all when we use `await []` 5 | 6 | const f1 = async () => { 7 | }; 8 | 9 | 10 | (async () => { 11 | const p1 = f1(); 12 | const p2 = f2(); 13 | const p3 = f3(); 14 | // Now p1, p2, p3 are instances of Promise 15 | // Place your code here 16 | await [p1, p2, p3]; 17 | })(); 18 | 19 | // Do not change line: `await [p1, p2, p3]`. 20 | // You need to change array behaviour. 21 | -------------------------------------------------------------------------------- /JavaScript/5-Await-Array/2-gpt-4o.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* Prompt: 4 | 5 | // Please propose solution to have behavior like 6 | // Promise.all when we use `await []` 7 | 8 | (async () => { 9 | const p1 = f1(); 10 | const p2 = f2(); 11 | const p3 = f3(); 12 | // Now p1, p2, p3 are instances of Promise 13 | // Place your code here 14 | await [p1, p2, p3]; 15 | })(); 16 | 17 | // Do not change line: `await [p1, p2, p3]`. 18 | // You need to change array behaviour. 19 | 20 | */ 21 | 22 | // Answer: 23 | 24 | // To achieve the behavior of `Promise.all` when using 25 | // `await [p1, p2, p3]` without changing that line, 26 | // you can modify the array prototype to handle promises 27 | // correctly. Here's the solution: 28 | 29 | const p1 = f1(); 30 | const p2 = f2(); 31 | const p3 = f3(); 32 | 33 | // Enhance array prototype to handle promises 34 | 35 | Array.prototype.then = function (onFulfilled, onRejected) { 36 | return Promise.all(this).then(onFulfilled, onRejected); 37 | }; 38 | 39 | await [p1, p2, p3]; 40 | 41 | // This way, the array `[p1, p2, p3]` will behave like 42 | // `Promise.all([p1, p2, p3])` when awaited. 43 | -------------------------------------------------------------------------------- /JavaScript/6-Await-null/1-initial.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Prompt: 4 | // Please describe control flow and async behavior in following code: 5 | 6 | let i = 0; 7 | 8 | const f1 = async () => { 9 | console.log(i++); 10 | await f1(); 11 | }; 12 | 13 | f1(); 14 | 15 | // After running last one we get output: 16 | 17 | /* 18 | ``` 19 | 1 20 | 2 21 | 3 22 | ... 23 | 8876 24 | 8877 25 | 8878 26 | Exception in PromiseRejectCallback: 27 | /Testing/JavaScript/test.js:7 28 | } 29 | ^ 30 | 31 | RangeError: Maximum call stack size exceeded 32 | 33 | Exception in PromiseRejectCallback: 34 | /Testing/JavaScript/test.js:6 35 | await f1(); 36 | ^ 37 | 38 | RangeError: Maximum call stack size exceeded 39 | 40 | node:internal/util/inspect:1585 41 | if (ObjectIs(number, -0)) { 42 | ^ 43 | 44 | RangeError: Maximum call stack size exceeded 45 | at is () 46 | at formatNumber (node:internal/util/inspect:1585:9) 47 | at formatPrimitive (node:internal/util/inspect:1643:12) 48 | at formatValue (node:internal/util/inspect:770:12) 49 | at inspect (node:internal/util/inspect:364:10) 50 | at formatWithOptionsInternal (node:internal/util/inspect:2279:40) 51 | at formatWithOptions (node:internal/util/inspect:2141:10) 52 | at console.value (node:internal/console/constructor:343:14) 53 | at console.log (node:internal/console/constructor:380:61) 54 | at f1 (/Testing/JavaScript/test.js:4:11) 55 | 56 | Node.js v18.20.0 57 | ``` 58 | */ 59 | 60 | // Please propose solution how can we avoid stack overflow in this code. 61 | -------------------------------------------------------------------------------- /JavaScript/6-Await-null/2-expected.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | let i = 0; 4 | 5 | const f1 = async () => { 6 | console.log(i++); 7 | await null; // or any non-promise or even non-thenable 8 | await f1(); 9 | }; 10 | 11 | f1(); 12 | -------------------------------------------------------------------------------- /JavaScript/6-Await-null/3-gpt-4o.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | let i = 0; 4 | 5 | const f1 = async () => { 6 | console.log(i++); 7 | await null; // or any non-promise or even non-thenable 8 | await f1(); 9 | }; 10 | 11 | f1(); 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023-2024 How.Programming.Works contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Применение Chat GPT в оптимизации JavaScript для Node.js](https://img.youtube.com/vi/Ebrzqj8cGUY/0.jpg)](https://www.youtube.com/watch?v=Ebrzqj8cGUY) 2 | 3 | [![Новые 3 задачи для GPT 4o](https://img.youtube.com/vi/L4SWquoMK2c/0.jpg)](https://www.youtube.com/watch?v=L4SWquoMK2c) 4 | --------------------------------------------------------------------------------