JSFiddle - React, Tailwind, and code Playground
by Ian Sanders
JavaScript
function scan(func, accum, [firstItem, ...otherItems]) {
if (firstItem === undefined) {
return [accum];
} else {
return [accum, ...scan(func, func(accum, firstItem), otherItems)];
}
}
function scan1(func, [firstItem, ...otherItems]) {
if (firstItem === undefined) {
return [];
} else {
return scan(func, firstItem, otherItems);
}
}
function add(a, b) {
return (a + b);
}
const data = [0, 1, 2, 3, 4, 5];
console.log(scan(add, 0, data))
// [ 0, 0, 1, 3, 6, 10, 15 ]
console.log(scan(Math.max, 3, data))
// [ 3, 3, 3, 3, 3, 4, 5 ]
console.log(scan(add, 0, []))
// [ 0 ]
console.log(scan1(add, data))
// [ 0, 1, 3, 6, 10, 15 ]
console.log(scan1(Math.max, data))
// [ 0, 1, 2, 3, 4, 5 ]
console.log(scan1(Math.min, data))
// [ 0, 0, 0, 0, 0, 0 ]
console.log(scan1(add, []))
// []