Skip to content

Instantly share code, notes, and snippets.

@defims
Forked from softprops/LICENSE.txt
Created June 14, 2016 01:22
Show Gist options
  • Save defims/8eeefdbeac63238f87e1b19ace0a0480 to your computer and use it in GitHub Desktop.
Save defims/8eeefdbeac63238f87e1b19ace0a0480 to your computer and use it in GitHub Desktop.
foldl
function(f) { // a function that takes 2 args
// 1) an accumulated value
// 2) a single value from a list
// and returns a value which represents
// the accumulated computation
return function( // returns a function `curry`
i, // an initial value for the accumulator
l // a list of values
) {
return l.length ? arguments.callee( // recurse if length > 0
f(i, l[0]), l.slice(1)
) : i; // else return the aggregation
}
}
export function(f){return function(i,l){return l.length?arguments.callee(f(i,l[0]),l.slice(1)):i;}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "foldl",
"description": "JavaScript fold left function application",
"keywords": ["fp","functional","array"],
"version": "0.1.0"
}
<html><head><script type="text/javascript">
var foldl = function(f){return function(i,l){return l.length?arguments.callee(f(i,l[0]),l.slice(1)):i;}}
var sum = foldl(function(a,e){
return a + e;
})
console.log(sum(0, [1,2,3,4])) // 10
var product = foldl(function(a, e) {
return a * e;
})
console.log(product(1, [1, 2, 3, 4]))
var names = foldl(function(a, e) {
a.push(e.name)
return a
})
console.log(names([],[{name:"a"},{name:"b"},{name:"c"}]))
</script></head><body></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment