Last active
August 5, 2016 14:49
-
-
Save CYBAI/be52f03ba8d6591fd40a4675c2efcdc0 to your computer and use it in GitHub Desktop.
Fix step3 in `transducing in javascript` from `getify`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And since
map(identity) == identity