Skip to content

Instantly share code, notes, and snippets.

@CYBAI
Last active August 5, 2016 14:49
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 CYBAI/be52f03ba8d6591fd40a4675c2efcdc0 to your computer and use it in GitHub Desktop.
Save CYBAI/be52f03ba8d6591fd40a4675c2efcdc0 to your computer and use it in GitHub Desktop.
Fix step3 in `transducing in javascript` from `getify`
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 need to use this function
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];
list
.reduce( mapReducer(add1)(listReduction), [] )
.reduce( filterReducer(isOdd)(listReduction), [] )
.reduce( reduceReducer(sum));
@DrBoolean
Copy link

And since map(identity) == identity

reduceReducer(sum) ==
mapReducer(identity)(sum) ==
id(sum) ==
sum

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment