Builds an array, using an iterator function and an initial seed value.
while
loop and Array.prototype.push()
to call the function repeatedly until it returns false
.seed
) and must always return an array with two elements ([value
, nextSeed
]) or false
to terminate.const unfold = (fn, seed) => {
let result = [],
val = [null, seed];
while ((val = fn(val[1]))) result.push(val[0]);
return result;
};
var f = n => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]
Would you like to help us improve 30 seconds of code?Take a quick survey
JavaScript, Function
Chunks an iterable into smaller arrays of a specified size.
JavaScript, Function
Converts the output of a generator function to an array.
JavaScript, Function
Creates a generator, that generates all values in the given range using the given step.