Last active
August 29, 2015 13:56
-
-
Save SegFaultAX/9303938 to your computer and use it in GitHub Desktop.
functional.js
This file contains hidden or 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 argList(args) { | |
return Array.prototype.slice.call(args); | |
} | |
function reduce0(fn, l, init) { | |
for(var i = 0; i < l.length; i++) { | |
init = fn(init, l[i]); | |
} | |
return init; | |
} | |
function reduce(fn, l, init) { | |
if (init === undefined) { | |
init = l[0], l = l.slice(1); | |
} | |
return reduce0(fn, l, init); | |
} | |
function map(fn, l) { | |
return reduce(function(acc, e) { | |
acc.push(fn(e)); | |
return acc; | |
}, l, []); | |
} | |
function filter(fn, l) { | |
return reduce(function(acc, e) { | |
if (fn(e)) { | |
acc.push(e); | |
} | |
return acc; | |
}, l, []); | |
} | |
function concat() { | |
var args = argList(arguments); | |
return reduce(function(acc, e) { | |
return Array.prototype.concat.call(acc, e); | |
}, args, []); | |
} | |
function mapcat(fn, l) { | |
return reduce(function(acc, e) { | |
return concat(acc, fn(e)); | |
}, l, []); | |
} | |
function partial(f) { | |
var args = argList(arguments).slice(1); | |
return function() { | |
return f.apply(null, concat(args, argList(arguments))); | |
} | |
} | |
function compose0(f, g) { | |
return function() { | |
var args = argList(arguments); | |
return f(g.apply(null, args)); | |
} | |
} | |
function compose() { | |
return reduce(compose0, argList(arguments)); | |
} | |
function juxt() { | |
var fns = argList(arguments); | |
return function() { | |
var args = argList(arguments); | |
return map(function(f) { return f.apply(null, args) }, fns); | |
} | |
} | |
var inc = function(n) { return n + 1; } | |
var even = function(n) { return n % 2 == 0; } | |
var add = function(a, b) { return a + b; } | |
var mul = function(a, b) { return a * b; } | |
var double = partial(mul, 2); | |
var incDouble = compose(double, inc); | |
var both = juxt(inc, double); | |
console.log(map(inc, [1,2,3,4])); | |
console.log(filter(even, [1,2,3,4,5])); | |
console.log(reduce(add, [1])); | |
console.log(concat([1,2,3], [4,5,6])); | |
console.log(mapcat(both, [1,2,3])); | |
console.log(double(10)); | |
console.log(incDouble(10)); | |
console.log(both(10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment