Problem
You want to be sure that the logic inside a function is executed only once.
Ingredients
- a self-defining function
Directions
-
Given: a function that is called twice, but should not do anything the second time it is called.
function printSomething() { console.log('something'); } printSomething(); // (1) Ok printSomething(); // (2) Should not be allowed -
Add a variable to memorize if the function has been called.
function printSomething() { let called = false; console.log('something'); } -
If it is
false, then returnundefined.function printSomething() { let called = false; if(called) { return undefined; } console.log('something'); } -
… otherwise set the variable to
true…function printSomething() { let called = false; if(called) { return undefined; } else { called = true; } } -
… execute the remaining logic of the function …
function printSomething() { let called = false; if(called) { return undefined; } else { called = true; console.log('something'); } } -
… and overwrite the function to do nothing.
function printSomething() { let called = false; if(called) { return undefined; } else { called = true; console.log('something'); printSomething = function() {}; } } -
Voilá, now if
printSomething()is called a second time, it simply does nothing.printSomething(); // (1) Ok printSomething(); // (2) Does nothingNotes
- A function that overwrite itself is also called a self-defining function.
Alternative recipes
- In tomorrow’s recipe we will see how to further improve the shown recipe.