// The param passed to `finalSum` is the last tail (eg. [3]),
// that's why we don't need to provide any sum function to it,
// because it will never be used.
constfinalSum=sumFactory(/*no need any other sum here*/);
constanotherSum=sumFactory(finalSum);
constsum1=sumFactory(anotherSum);
console.log(sum1([1,2,3]))// -> 6
// This is using Y combinator to make the `sumFactory`
// become a function that can be run automatically
constsum2=Y(sumFactory)
returnsum2(arrayOfNumber);
}
functionY(f){
return(
// In JS, we can not omit the argument `a`,
// since JS is not lazy evaluation by default,
// hence it will cause stack overflow. This version
// of Y combinator is called Z combinator.
// It's ok to omit `a` is language that supports
// lazy evaluation, like Haskell
m=>a=>f(m(m))(a)// This line can be replaced with `x => x(x)`
)(
m=>a=>f(m(m))(a)
);
}
functionsumFactory(sum){
returnfunction(arr){
const[head,...tail]=arr;
if(tail.length===0)returnhead;
returnhead+sum(tail);
}
}
arrayOfNumber=[1,2,3,4,5,6,7]
Purpose-built for displays of data
Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.