From 421d7964e5ce397400ce04e69b52f819ed3a64c2 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 24 Jan 2018 16:22:14 +0200 Subject: [PATCH] Add unfold Similar to Ramda's unfold --- snippets/unfold.md | 20 ++++++++++++++++++++ tag_database | 1 + 2 files changed, 21 insertions(+) create mode 100644 snippets/unfold.md diff --git a/snippets/unfold.md b/snippets/unfold.md new file mode 100644 index 000000000..ff161aa91 --- /dev/null +++ b/snippets/unfold.md @@ -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] +``` diff --git a/tag_database b/tag_database index c48aed7e1..b5ea61b91 100644 --- a/tag_database +++ b/tag_database @@ -230,6 +230,7 @@ truncateString:string truthCheckCollection:object,logic,array unary:adapter,function unescapeHTML:string,browser +unfold:function,array union:array,math unionBy:array,function unionWith:array,function