Javascript

How to create a revocable function to grant/revoke access to any other function?

The following code will show you how to create a function ‘revocable’ that will be used to grant/revoke access to other functions.

The function that will be tested here is the add function to add 2 numbers. But the ‘revocable’ function is good enough to work for other functions as well.

function add (x, y) {
    return x + y;
}

Given below is the code for the ‘revocable’ function:

function revocable(fn) {
    var allow = true;
    return {
        invoke: function() {
            if(!allow) {
                throw new Error('Access revoked');
            }
            return fn.apply(this, arguments);
        },
        revoke: function() {
            allow = false;
        },
        grant: function() {
            allow = true;
        }
    }
}

var temp = revocable(add);

temp.invoke(3, 4); // 7

temp.revoke();

temp.invoke(3, 4); // Uncaught Error: Access revoked(…)

temp.grant();

temp.invoke(3, 4); // 7
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s