Skip to content

Add ability to chunk array by function #46

Closed
sp3ber opened this issue Jul 11, 2019 · 0 comments · Fixed by #48
Closed

Add ability to chunk array by function #46

sp3ber opened this issue Jul 11, 2019 · 0 comments · Fixed by #48

Comments

@sp3ber
Copy link

sp3ber commented Jul 11, 2019

Sometimes (not often) i need logic like this:

const positiveNumbers = numbers.filter(isPositiveNumber)
const negativeNumbers = numbers.filter(complement(isPositiveNumbers))
/// some tramsforms of this values
...

so it's not very fast and declarative. Also it becomes too repetetive, when there are more then 2 groups. So I need something like this:

const [positiveNumbers, negativeNumbers] = groupByArrays([isPositiveNumber], list);

So I mean that i can pick my sublist by index/
Also there is other usecase with more than 2 groups:

const [positiveNumbers, negativeNumbers, strings, rest] = groupByArrays([isPositiveNumber, isNegativeNumber, isString], list);

So realization can be something like this:

groupByArrays = (fns, arr) => {
    const result = [];
    let a, b = arr;
    
    return fns.map((fn) => {
        [a, b] = partition(fn, b);
        
        return a;
    }).concat([b])
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant