When coding, we should always aim to make our programs as efficient as possible. Memoisation is a technique whereby we speed up expensive computer operations by caching the result...allowing subsequent calls to fetch the result from the cache instead of reprocessing the time-consuming operation.
Below is an example of JavaScript Memoisation in action. Here we're simple calculating whether a number is a prime number. This will be an expensive operation as we're going to iterate through numbers looking for a whole-number factor. When we find a result (true or false), we store it in an array (our cache). Next time the function is run, we check the array for the corresponding result..if it is found, return it...if not, calculate the result, store it in the array and then return it.
Try testing the example below with an input of 6700417 - console.log(isPrime(6700417));.
After the function returns a result, try again. The second time will be considerably faster than the first time!
For a couple of related examples, check out the following GitHub Gist: Simple JavaScript storing and self-memoising function examples.
function isPrime(value){
//Create the cache on the first run through.
//The cache is created as a property of the function.
if(!isPrime.answers) isPrime.answers = {};
//Check the cache for the current value, return it if found.
if(isPrime.answers[value] != null){
return isPrime.answers[value];
}
//Otherwise, compute result
//1 is never a prime number
var prime = value != 1;
//Run through numbers and check for a whole-number factor.
for(var i = 2; i < value; i++){
if (value % i == 0){
prime = false;
break;
}
}
//Return the boolean result and assign it to the cache.
return isPrime.answers[value] = prime;
}