This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Example: https://repl.it/repls/WhoppingPotableBoards | |
| function lazyArray(data, func) { | |
| const out = []; | |
| for (let i = 0; i < data.length; i++) { | |
| function set(value) { | |
| delete out[i]; | |
| return out[i] = value; | |
| } | |
| Object.defineProperty(out, i.toString(), { | |
| configurable: true, | |
| enumerable: true, | |
| set, get: () => set(func(data[i])), | |
| }); | |
| } | |
| return out; | |
| } | |
| /** | |
| * Will act like an array but when accessing an index for the first time the function will be evaluated. | |
| */ | |
| const a = lazyArray([1, 2, 3, 4], x => x * x); |