Memoization lets a function reuse a result instead of recalculating it. Store each result alongside its input; when the same input comes around again, return the cached result. In JavaScript, a function property can hold the cache. section 3.2.2 section 3.2
A self-memoizing function follows this cycle:
- Create the cache the first time the function is called. section 3.2.2
- Check whether the input already has a cached result; return it if found. section 3.2.2
- Otherwise, calculate the result, store it with the input, and return it. The cache remains as long as the function does. section 3.2.2
Caching a prime-number check
The isPrime function stores true or false for each value it checks. Assertions verify both that 5 is prime and that its answer was cached. section 3.2.2
Listing 3.3. Memoizing previously computed values
function isPrime(value){
if (!isPrime.answers){ #A
isPrime.answers = {}; #A
} #A
if (isPrime.answers[value] !== undefined) { #B
return isPrime.answers[value]; #B
} #B
var prime = value !== 1; // 1 is not a prime
for (var i = 2; i < value; i++) {
if (value % i === 0) {
prime = false;
break;
}
}
return isPrime.answers[value] = prime; #C
}
assert(isPrime(5), "5 is prime!" ); #D
assert(isPrime.answers[5], "The answer was cached!" ); #D
See the complete isPrime implementation, including cache initialization, lookup, and result storage. section 3.2.2







