Wednesday, December 18, 2013

JavaScript Pearl: Self-defining Functions

Here's a neat trick that I learned from Stoyan Stefanov's great book JavaScript Patterns.

If you have a function that is called several times during program execution, but that has some prep work that needs to be done only once, we can have our function do whatever upfront work it needs to do and then redefine itself.

Here's a simple example - the prep work that the function will do is to generate and return some random number. Subsequent runs should return the same number as the first run.

var foo = function() {
  var i = Math.floor(Math.random()*100) + 1; //generate some number between 1-100
  foo = function() { return i; }; //here we redefine foo() and fix i in our closure, which is still available in subsequent runs
  return i;
}; 


Here is example output from running the code

> foo(); //should return some random number
   21

> foo(); //should return the same number as the first call
   21



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.