Suppose you have to partition an array of number given some predicates, how would you procede ?
I want for example, partition an array given the following predicates :
[
(x) => x % 3 == 0,
(x) => x % 4 == 0
]
Below the partition function.
The nice thing is that we do all the treatment in one pass, without relying on the filter method.
Thanks to the reduce method.
function partition(data, predicates = []) {
const lp = predicates.length;
return data.reduce((buckets, element) => {
for (j = 0; j < lp; j++) {
if (predicates[j](element)) {
buckets[j].push(element);
}
}
return buckets.map(t => t.sort((x,y) => x - y));
},
// Here we create as many arrays (buckets) as predicates
// This array of 'buckets' constitute the accumulator
// of the reducer.
[...Array(lp)].map(() => []));
}
const a = [16,8,1,27,3,2,4,6,9,11]
console.log(
partition(a, [
(x) => x % 3 == 0,
(x) => x % 4 == 0
])
)
You can play with it here Partition
Result :
[ [ 3, 6, 9, 27 ], [ 4, 8, 16 ] ]
Don't hesitate to comment, correct or enhance.
Top comments (0)