Crockford's Problems 1 - 5

Problems with functions

by mrrodd

JavaScript

// Write two binary functions (add and mul)
// that take two numbers and return their sum
// and product.
function add(x, y) {
    return x + y;
}

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

// Write a function that takes an argument and 
// returns a function that returns that argument.
function identityf(x) {    
    return function() {
        return x;
    };
}

// Write a function that adds from two invocations.
// addf(3)(4)
function addf(x) {
    return function(y) {
        return x + y;
    };
}

// Write a function that takes a binary function
// and makes it callable with two invocations.
function applyf(method) {
    return function(x) {
        return function(y) {
            return method(x, y);
        };
    };
}
// console.log( applyf(mul)(5)(6) );  // 30