The best way to improve the performance of an operation is to not perform it—at least not twice, or worse, hundreds or thousands of times. Repeating costly computations is an unnecessary waste of CPU cycles and can be avoided by caching the results. The memoize()
function helps us here, by caching the results of the called function for later use. However, caching has its own overheads and pitfalls to be aware of. Let's start by taking a look at idempotent functions—these always produce the same output when given the same input arguments:
function primeFactors(number) { var factors = [], divisor = 2; while (number > 1) { while (number % divisor === 0) { factors.push(divisor); number /= divisor; } divisor += 1; if (divisor * divisor > number) { if (number > 1) { factors.push(number); } break; } } return factors; } var collection...