Skip to content

Instantly share code, notes, and snippets.

@softprops
Created April 28, 2011 12:24
Show Gist options
  • Save softprops/946248 to your computer and use it in GitHub Desktop.
Save softprops/946248 to your computer and use it in GitHub Desktop.
functional fold in javascript
var foldl = function(f, init, l) {
switch(l.length) {
case 0: return init;
default: return arguments.callee(
f, f(init, l[0]), l.slice(1)
);
}
};
var foldr = function(f, init, l) {
return foldl(f, init, l.reverse());
};
Copy link

ghost commented Sep 18, 2017

(function() {
  var foldl = function(f, ac, xs) {
    return (xs.length === 0) && ac
      || foldl(f, f(ac, xs[0]), xs.slice(1));
  };
  console.log(
    foldl((x,y) => x+y, 0, [1,2,3]) === 6 // true
  );
})();

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