Question:

Describe what happens when the Helpers.factorial(3) function is run twice.

var Helpers = {
  cache: {},
  factorial: function (n) {
    if (this.cache[n]) { return this.cache[n]; };
    var counter = 1;
    var result = 1;
    while (counter <= n) {
      result *= counter;
      counter++;
    }
    this.cache[n] = result;
    return result;
  }
}

Helpers.factorial(3)
Helpers.factorial(3)

Answer:

The factorial is cached in an object, so it does not need to be recomputed if it has already been calculated. When Helpers.factorial(3) is initially run, the factorial is computed and cached. When Helpers.factorial(3) is run again, the cached value is returned without performing the computations again.

Caching requires extra memory and makes the code more complex, but it is a very useful tactic for expensive calculations. Caching is also referred to as memoization.


Keywords:

© 2017 QuizBucket.org