- No danger for you, just squeamish about recommending anyone to experiment at all with (or even be conscious of the whereabouts of) a file which contains so much work and resource
- Reduce is JavaScript's version of fold or foldl / foldLeft, which is just a very general relationship between a list and any single value which can be derived from it. See more below.
- The same function is used in two places there, one inside the reduce and one outside, so to minimize maintenance I just bound a name to it in one place.
The short version of fold (reduce) was recently tweeted as:
A fuller version, worth skimming, I think, because fold/reduce is so universal and powerful, is at:
And here are some simple illustrative folds (most of them left folds, one of them a right fold (reduceRight in JS). A surprising number of things, even map and filter, can be written as a fold. Good instrument to have in the toolbag.
(function () {
'use strict';
// sum :: [Number] -> Number
function sum(lstNumbers) {
return lstNumbers
.reduce(
function (accumulator, x) {
return accumulator + x;
},
0 // initial value of accumulator
)
}
// length :: [a] -> Integer
function length(ListOfAnything) {
return ListOfAnything
.reduce(
function (accumulator, x) {
return accumulator + 1;
},
0 // initial value of accumulator
)
}
// filtered :: (a -> Bool) -> [a] -> [a]
function filtered(f, lst) {
return lst
.reduce(
function (accumulator, x) {
return (
f(x) && accumulator.push(x),
accumulator
)
}, [] // initial value of accumulator is empty list
)
}
// reversed :: [a] -> [a]
function reversed(lst) {
return lst
.reduceRight(
function (accumulator, x) {
return (
accumulator.push(x),
accumulator
);
}, [] // initial value of accumulator is empty list
)
}
function isEven(n) {
return n % 2 === 0
}
return {
sum: sum([1, 2, 3, 4, 5, 6, 7, 8, 9]),
length: length([1, 2, 3, 4, 5, 6, 7, 8, 9]),
filtered: filtered(isEven, [1, 2, 3, 4, 5, 6, 7, 8, 9]),
reversed: reversed([1, 2, 3, 4, 5, 6, 7, 8, 9])
}
})();