Question

Is there an official term or word for a function that will only execute once? The easiest example I can think of is a javascript function in a closure like this. (taken from here)

function createChance() {
  var chanceLeft = true;
  return function() {
      if (chanceLeft) {
          console.log("This was the only chance you had.");
          chanceLeft = false;
      } else {
          console.log('Sorry: you already used your chance');
      }
  };
}

var chance = createChance();
chance();
// This was the only chance you had.
chance();
// Sorry: you already used your chance
Was it helpful?

Solution

This is called an idempotent function. No mater how many times you call it, it will return the same result after the initial run. There is a very good explanations (though note the comments on the accepted answer for caveats) on other questions.

This blog posting explains several idempotent vs. non-idempotent scenarios. I've pasted a snippet below in the event the posting disappears in the future.

Shopping Cart Example:

  • Not idempotent: Pushing "Place order" creates a new order in the database.
  • Idempotent: Pushing "Place order" moves order 4567 from 'cart' to 'finalized' status.

Real world example

  • Idempotent: Give me that pizza.
  • Not idempotent: Make me a pizza.

Password checking example

  • Idempotent: check a password against the hash in the database
  • Not idempotent: check a password and increment the bad-login-attempts if it's wrong

Installing software example

  • Not idempotent: Install MongoDB
  • Idempotent: Install MongoDB if it isn't already installed

As you can see by those examples, and your question, an idempotent function has no effect on the second, third, ten thousandth, etc. run. It's a common paradigm in many applications, even if it wasn't designed with the word 'idempotent' in mind.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top