774 B
774 B
title, tags, expertise, cover, firstSeen, lastUpdated
| title | tags | expertise | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Unfold array | function,array | intermediate | blog_images/dog-waiting.jpg | 2018-01-24T16:22:14+02:00 | 2020-09-15T16:28:04+03:00 |
Builds an array, using an iterator function and an initial seed value.
- Use a
whileloop andArray.prototype.push()to call the function repeatedly until it returnsfalse. - The iterator function accepts one argument (
seed) and must always return an array with two elements ([value,nextSeed]) orfalseto 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]