Is there an elegant, functional way to turn this array:
[ 1, 5, 9, 21 ]
into this
[ [1, 5], [5, 9], [9, 21] ]
I kn
I noticed that the current solutions, in a way, all look ahead or behind (arr[i + 1] or arr[i - 1]).
It might be useful to also explore an approach that uses reduce and an additional array, defined within a function's closure, to store a to-be-completed partition.
Notes:
part doesn't have to be an array when working with only 2 items, but by using an array, we extend the method to work for n-sized sets of itemsshift, you can use a combination of slice and redefine part, but I think it's safe here.length less than the required number of elements are not returnedconst partition = partitionSize => arr => {
const part = [];
return arr.reduce((parts, x) => {
part.push(x);
if (part.length === partitionSize) {
parts.push(part.slice());
part.shift();
}
return parts;
}, []);
};
const makePairs = partition(2);
const makeTrios = partition(3);
const pairs = makePairs([1,2,3,4,5,6]);
const trios = makeTrios([1,2,3,4,5,6]);
console.log("partition(2)", JSON.stringify(pairs));
console.log("partition(3)", JSON.stringify(trios));