Skip to content

Instantly share code, notes, and snippets.

@Mechazawa
Last active June 20, 2018 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mechazawa/01b611ec9d4990a750d9487abb4df7d1 to your computer and use it in GitHub Desktop.
Save Mechazawa/01b611ec9d4990a750d9487abb4df7d1 to your computer and use it in GitHub Desktop.
// 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