Crockford's Problems 6 - 9
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);
};
}
//console.log( curry(mul, 5)(6) );
// Write methodize, a function that converts a
// binary function to a method.
function methodize(func){
return function(x) {
return func(this, x);
};
}
Number.prototype.add = methodize(add);
//console.log( (3).add(4) );
// Write demethodize, a function that converts a
// method to a binary function.
function demethodize(func) {
return function(that, y) {
return func.call(that, y);
};
}
console.log( demethodize(Number.prototype.add)(5, 6) );