Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created February 17, 2017 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/72d9b14c83d984136144368b53624ccb to your computer and use it in GitHub Desktop.
Save tmcw/72d9b14c83d984136144368b53624ccb to your computer and use it in GitHub Desktop.
function introduce(fn, memo, dependents) {
return (function(memo) {
dependents = dependents || [];
return function(item) {
return item === undefined ? memo : memo = fn.apply(undefined, [item, memo].concat(dependents.map(d => d(item))));
};
}).bind(undefined, memo);
}
var createSum = module.exports.createSum = introduce((item, sum) => sum + item, 0);
var createCount = module.exports.createCount = introduce((item, count) => ++count, 0);
var createMean = module.exports.createMean = introduce((item, last, sum, count) => sum / count, undefined, [
createSum(),
createCount()
]);
var createMin = module.exports.createMin = introduce(
(item, min) => min === undefined || item < min ? item : min,
undefined
);
var createMax = module.exports.createMax = introduce(
(item, max) => max === undefined || item > max ? item : max,
undefined
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment