Last active
August 5, 2016 14:42
-
-
Save DrBoolean/20dcba4af7eab5d862fbc5d9505e8565 to your computer and use it in GitHub Desktop.
step3.js
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 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 |
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 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