Add bifurcate, bifurcateBy

This commit is contained in:
Angelos Chalaris
2018-02-14 12:13:07 +02:00
parent 4b9d00fe11
commit a1a99021d3
8 changed files with 90 additions and 4 deletions

17
snippets/bifurcate.md Normal file
View File

@ -0,0 +1,17 @@
### bifurcate
Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on `filter`.
```js
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [
[],
[],
]);
```
```js
bifurcate([ 'beep', 'boop', 'foo', 'bar' ], [ true, true, false, true ]); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```

17
snippets/bifurcateBy.md Normal file
View File

@ -0,0 +1,17 @@
### bifurcateBy
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on the value returned by `fn` for each element.
```js
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [
[],
[],
]);
```
```js
bifurcateBy([ 'beep', 'boop', 'foo', 'bar' ], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```