Add unfold

Similar to Ramda's unfold
This commit is contained in:
Angelos Chalaris
2018-01-24 16:22:14 +02:00
parent 3869478fb9
commit 421d7964e5
2 changed files with 21 additions and 0 deletions

20
snippets/unfold.md Normal file
View File

@ -0,0 +1,20 @@
### unfold
Builds an array, using an iterator function and an initial seed value.
Use a `while` loop and `Array.push()` to call the function repeatedly until it returns `false`.
The iterator function accepts one argument (`seed`) and must always return an array with two elements ([`value`, `nextSeed`]) or `false` to terminate.
```js
const unfold = (fn, seed) => {
let result = [],
val = [null, seed];
while ((val = fn(val[1]))) result.push(val[0]);
return result;
};
```
```js
var f = n => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]
```