functional.js

functional.js

docs / source

@lee_crossley / ilee.co.uk

Straight in...


var enabledProducts = [];

for (var i = 0; i < products.length; i++) {
    if (products[i].enabled) {
        enabledProducts.push(products[i]);
    }
}
                

With fjs


var enabledProducts = fjs.select(function(item) {
    return item.enabled;
}, products);
                

view in docs

Skinning the cat


var enabledProducts = fjs.select(function(item) {
    return item.enabled;
}, products);
                

Currying for reuse


var enabled = function (item) {
    return item.enabled;
};

var selectEnabled = fjs.select(enabled);

selectEnabled(products);
                

view in docs

More techniques

Lambda expressions


var enabledProducts = fjs.select("p => p.enabled", products);
                

Curried lambda expression


var selectEnabled = fjs.select("p => p.enabled");

selectEnabled(products);
                

view in docs

fjs functions for collections

each, map, reduce, fold, apply, every, any, select, pluck, toArray, first, last, best, partition, group, while

view in docs

Fold product prices


var add = function (a, b) {
    return a + b;
};

var sum = fjs.fold(add, 0);

sum(prices);
                

fjs.fold("a, b => a + b", 0, prices);
                

view in docs

From the DOM


var $ = document.querySelectorAll.bind(document);

var prices = [].slice.call($(".price"));

fjs.fold("a, b => a + b", 0, prices);
                

view in docs

Roll your own


var converter = fjs.curry(function(rate, symbol, input) {
    var output = input * rate;
    return symbol + output.toFixed(2);
});

var poundsToUSD = converter(1.52, "$");
var poundsToEUR = converter(1.27, "€");

poundsToUSD(100);
poundsToEUR(50);
                

view in docs

Why fjs?

  • Functional from the ground up but still JS
  • Consistent implementation
  • Client (cross browser, mobile) / Server (nodejs)
  • < 2kB minified and gzipped
  • Best curry you'll get anywhere

There's much, much more

  • Multiple function composition with fjs.compose
  • Extending function arity beyond the expected length

Try it

  • npm install functional.js --save
  • bower install functional.js
  • http://bit.ly/funcmin
  • here (open your dev console)

Get involved