lazyMap.js

1 min read Original article ↗
// 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);