Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Thursday, 19 June 2014

JavaScript function that can be called only once

function add(a, b) {
return a+b;
}

function once(func) {
return function () {
var f = func;
func = null;
return f.apply(
this,
arguments
);
};
}

var add_once = once(add);
console.log(add_once(3, 4)); // 7
console.log(add_once(3, 4)); // throws as f is now null

JSFiddle: http://jsfiddle.net/stevenhollidge/uA6TH/


But I prefer the following code as it’s more readable:

function add(a, b) {
return a+b;
}

function once(func) {
var usageCount = 0;

return function () {
if (usageCount === 1) {
throw 'Already used';
}
usageCount += 1;
return func.apply(
this,
arguments
);

}
}

var add_once = once(add);
console.log(add_once(3, 4)); // 7
console.log(add_once(3, 4)); // throws

JSFiddle: http://jsfiddle.net/stevenhollidge/eqnU3/