Skip to content

Instantly share code, notes, and snippets.

@DrBoolean
Last active August 5, 2016 14:42
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 DrBoolean/20dcba4af7eab5d862fbc5d9505e8565 to your computer and use it in GitHub Desktop.
Save DrBoolean/20dcba4af7eab5d862fbc5d9505e8565 to your computer and use it in GitHub Desktop.
step3.js
function add1(v) { return v + 1; }
function isOdd(v) { return v % 2 == 1; }
function sum(total,v) { return total + v; }
function listReduction(list,v) {
list.push(v);
return list;
}
function mapReducer(fn) {
return function(reductionFn){
return function(list,v){
return reductionFn( list, fn(v) );
};
};
}
function filterReducer(fn) {
return function(reductionFn){
return function(list,v){
if (fn(v)) return reductionFn( list, v );
return list;
};
};
}
// no longer used
function listSumReduction(list,v) {
list[0] = sum(list[0] || 0,v);
return list;
}
function identity(v) { return v; }
// no longer used, but this is f-ing rad!
function reduceReducer(reductionFn){
return mapReducer(identity)(reductionFn);
}
var list = [2,5,8,11,14,17,20];
list
.reduce( mapReducer(add1)(listReduction), [] )
.reduce( filterReducer(isOdd)(listReduction), [] )
.reduce( sum, 0 ) // sum is a reduce, must start with 0
//48
function add1(v) { return v + 1; }
function isOdd(v) { return v % 2 == 1; }
function sum(total,v) { return total + v; }
function composeRight(fn1,fn2) {
return function(...args){
return fn1(fn2(...args));
};
}
function listReduction(list,v) {
list.push(v);
return list;
}
function mapReducer(fn) {
return function(reductionFn){
return function(list,v){
return reductionFn( list, fn(v) );
};
};
}
function filterReducer(fn) {
return function(reductionFn){
return function(list,v){
if (fn(v)) return reductionFn( list, v );
return list;
};
};
}
function listSumReduction(list,v) {
list[0] = sum(list[0] || 0,v);
return list;
}
function identity(v) { return v; }
function reduceReducer(reductionFn){
return mapReducer(identity)(reductionFn);
}
var list = [2,5,8,11,14,17,20];
var transducer =
composeRight(
mapReducer(add1),
filterReducer(isOdd)
)(sum)
list
.reduce( transducer, 0 );
// 48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment