Initial commit

master
Sven Slootweg 5 years ago
commit dd1e088dd5

@ -0,0 +1,40 @@
# split-filter
Like `Array#filter`, but you get to keep both pieces. Quite literally. Splits the array by a predicate function.
If you want to split an array into *more than two* arrays, you'll want to use [`split-filter-n`](https://www.npmjs.com/package/split-filter-n) instead.
## Example
```js
"use strict";
const splitFilter = require("./");
function isEven(number) {
return Math.abs(number) % 2 === 0;
}
let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];
let [ even, odd ] = splitFilter(numbers, (number) => isEven(number));
console.log(even); // [ 0, 2, 4, 6, 8 ]
console.log(odd); // [ 1, 3, 5, 7 ]
```
## API
### splitFilter(array, predicate)
Splits the `array` into a truthy and a falsy side, based on what the `predicate` function returns. Note that like `Array#map`, whether a value 'matches' depends on whether the returned value is [__truthy__](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), not just a literal `true`.
- __array:__ The array to split.
- __predicate:__ The function that determines which side to sort the value into.
Returns an array with two elements:
- __0:__ The elements that __matched__ the predicate function (ie. for which the predicate function returned a truthy value).
- __1:__ The elements that __did not match__ the predicate function (ie. returned a falsy value).
It's strongly recommended to use [array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring) in handling the returned array (like in the example), as this will greatly improve readability of your code.

@ -0,0 +1,14 @@
"use strict";
const splitFilter = require("./");
function isEven(number) {
return Math.abs(number) % 2 === 0;
}
let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];
let [ even, odd ] = splitFilter(numbers, (number) => isEven(number));
console.log(even); // [ 0, 2, 4, 6, 8 ]
console.log(odd); // [ 1, 3, 5, 7 ]

@ -0,0 +1,16 @@
"use strict";
module.exports = function splitFilter(array, predicate) {
let truthy = [];
let falsy = [];
for (let item of array) {
if (predicate(item)) {
truthy.push(item);
} else {
falsy.push(item);
}
}
return [ truthy, falsy ];
};

@ -0,0 +1,10 @@
{
"name": "split-filter",
"description": "Like Array#filter, but you get to keep both pieces",
"version": "1.0.0",
"main": "index.js",
"repository": "git@git.cryto.net:joepie91/node-split-filter.git",
"author": "Sven Slootweg <admin@cryto.net>",
"license": "WTFPL OR CC0-1.0",
"keywords": ["array", "filter", "split"]
}
Loading…
Cancel
Save