Crockford's Problems 13 - 15

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 allows another function
// to only be called once.
function myonce(f) {
    var canCall = true;
    return function(a, b) {
        if(canCall) {
            canCall = false;
            return f(a, b);
        } else {
            throw("function called more than once");
        }
    };
}

// Crockford's Once Solution
function once(func) {
    return function() {
        var f = func;
        func = null;
        return f.apply(this, arguments);        
    };
}

var add_once = myonce(add);
//console.log( add_once(3, 4) );
//console.log( add_once(3, 4) );


// Write a factory function that returns two functions
// that implement an up/down counter.
function counterf(a) {
    return {
        inc: function() { return a + 1; },
        dec: function() { return a - 1; }
    };  
}

//counter = counterf(10);
//console.log( counter.inc() );
//console.log( counter.dec() );

function nice(a) {
    return 'alert: ' + a;
}

function revocable(f) {
    return {
        invoke: function() {
            return f.apply(this, arguments);
        },
        revoke: function() { 
            f = null; 
        }
    };
}
temp = revocable(nice);
console.log( temp.invoke(7) );
temp.revoke();
console.log( temp.invoke(8) );