functools
- a minimal javascript library for functional programming
A typical usage:
var map = require("functools").map;
var seq = [3,1,4,1,5,9];
functools.map(function(el,ind,seq){
return el+ind;
},seq);
Function Composition:
var compose = require("functools").compose;
compose(select, update, prettify, display)("body .messages");
Currying:
var fn = require("functools");
var pickEvens = fn.curry(fn.filter)(function(num){ return num%2==0 });
pickEvens([3,1,4]) // returns [4]
pickEvens([1,5,9,2,6,5]) // returns [2,6]
Partial Function Application:
Foobar.prototype.doSomething = function(msg){
puts(msg);
this.corge();
}
server.on("connection", functools.partial(foobar.doSomething, ["Hello World"], foobar));
functools is a library for functional programming written in JavaScript. It's based on a CommonJS module consists of several function manipulation and list iteration tools.
Despite functools follows CommonJS specs, my actual aim is to improve the experience of DOM programming. Even functools is now ready to be built for browsers -and I'm also developing a web implementation of CommonJS- this version doesn't include a web build because I couldn't a suitable test tool with support of both v8/node and browsers.
Combine functions in a new one, passing the result of each function to next one, from left to right.
function cube(x){ return x*x*x };
compose(Math.sqrt,cube)(4); // returns 8
Transform multiple-argument function into a chain of functions that return each other until all arguments are gathered.
function sum(x,y){ return x+y; }
var add3 = curry(sum, 3);
add3(14); // returns 17
add3(20); // returns 23
Return a new function which will call function with the gathered arguments.
function testPartial(){
var args = reduce(function(x,y){ x+", "+y },arguments);
console.log("this:",this);
console.log("args:",args);
}
partial(testPartial, [3,14], 3.14159)(1,5,9);
The example code above will output:
this: 3.14159
args: 3,14,1,5,9
Call function once for element in iterable.
each(function(el,ind,list){ console.assert( el == list[ind] ); }, [3,1,4]);
Invoke function once for each element of iterable. Creates a new array containing the values returned by the function.
map(function(el,ind,list){ return el*el },[3,1,4,1,5,9]); // returns [9,1,16,1,25,81]
Construct a new list from those elements of iterable for which function returns true.
filter(function(el,ind,list){ return el%2==0 },[3,1,4]); // returns [4]
Apply function cumulatively to the items of iterable, as to reduce the iterable to a single value
reduce(function(x,y){ return x*y }, [3,1,4]); // returns 12