JavaScript Cool Stuff

From Code Self Study Wiki
Jump to: navigation, search

Beyond the basics.

Currying

Example 1

var babyAnimals = function(a) {
    return function(b) {
        var result = 'i love '.concat(a).concat(' and ').concat(b);
        return result;
    };
};
var babyKoala = babyAnimals('koalas'); // prefills a
babyKoala('elephants'); // fills b, returns: 'i love koalas and elephants'

Example 2

No curry:

function multiply(x, y) { return x * y; }

Add curry:

function curriedMultiply(x) {
  return function(y) { return x * y; }
}

curriedMultiply(3) does this:

function(y) {
  return 3 * y;
}

Custom Curry Functions