Algorithmic refactoring

To prove that we have an artificial problem on our hands, here is a much more efficient Fibonacci function:

exports.fibonacciLoop = function(n) { 
    var fibos = []; 
    fibos[0] = 0; 
    fibos[1] = 1; 
    fibos[2] = 1; 
    for (var i = 3; i <= n; i++) { 
        fibos[i] = fibos[i-2] + fibos[i-1]; 
    } 
    return fibos[n]; 
} 

If we substitute a call to math.fibonacciLoop in place of math.fibonacci, the fibotimes program runs much faster. Even this isn't the most efficient implementation; for example, a simple prewired lookup table is much faster at the cost of some memory.

Edit fibotimes.js as follows and rerun the script. The numbers will fly by so fast your head will spin:

for (var num = 1; num < 8000; num++) { let now = new Date().toISOString(); ...

Get Node.js Web Development - Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.