Crockford's Problem 10 - 12

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 a function and an argument,
// and returns a function that cna supply a second argument.
function curry(method, arg1) {
    return function(arg2) {
        return method(arg1, arg2);
    };
}

// Write a function 'twice' that takes a binary function and
// returns a unary function that passes its argument to the
// binary function 'twice'.
function twice(binary) {
    return function(x) {
        return binary(x, x);
    };
}

var dbl = twice(add);
var sqr = twice(mul);
//alert( dbl(11) );
//alert( sqr(11) );


// Write a function 'composeu' that takes two unary
// functions and returns a unary function that calls
// them both.
function composeu(f, g) {
    return function(a) {
        return g(f(a));
    };
}
//alert( composeu(dbl, sqr)(6) );

// Write a function 'composeb' that takes two binary 
// functions and returns a function that calls them
// both.
function composeb(f, g) {
    return function(a, b, c) {
        return g( f(a, b), c );
    };
}

alert( composeb(add, mul)(2, 3, 5) );