Last active
June 20, 2018 12:05
-
-
Save Mechazawa/01b611ec9d4990a750d9487abb4df7d1 to your computer and use it in GitHub Desktop.
This file contains 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment