It’s not that hard to implement the factorial effect, so let’s just go to the code

function factor (target){ for(let i =target; i>0; i--){ sum = sum * i; } return sum; } } console.log(factor(100));Copy the code

I’m just going to print it out, and you can see that it’s a big number,

If you think about it, there is one thing that can be improved: the for loop is done 100 times. Because we use let, each loop declares an address in memory to store the value of I, which is very memory consuming. So let can be changed to var, each time you change the value of the stored I address, the code will run much faster.

function factor (target){ for(var i =target; i>0; i--){ sum = sum * i; } return sum; } } console.log(factor(100));Copy the code

On second thought, 100! If you have to multiply all the way from 100 to 1 every time, a for loop 100 times is not only a waste of memory, but also very time consuming. Is there a way to improve efficiency and achieve a faster 100! ?

Yes, the answer is to use closures.

This is where you take advantage of closures and function memory.

A function can cache the result of a previous run in an object, and the next time it needs the value, it can call the value directly from the object, without recalculating, which increases efficiency greatly.

This is the simplest closure you can use to show the effect.

let map = new Map(); Var sum =1; var sum =1; Return function (target){if(map.has(target)){console.log(" Get the value in cache! "){console.log(" get the value in cache! ") ); return map.get(target); } for(var i =target; i>0; i--){ sum = sum * i; } map.set(target,sum); Return sum; // return sum; // return sum; // return sum; } } let sum = summaration(); Console. log(sum(100)); // Console. log(sum(100)); console.log("----------"); console.log(sum(100));Copy the code

The effect is as follows:

summary

Closures are not as simple as they seem; this is just the simplest form of closure. As the big guy said, you can use closures as knapsacks. When a function is created and passed or returned from another function, it carries a knapsack with all the variables.

Thanks for supporting original works