For Years I To Be Able To Know Tips On How To Save Cash

To keep ahead in this particular game of private finance, really set aim to master personal management of their bucks. You should make it possible for you give your financial health a “check up” at…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Memoized Functions with the Prototype Chain

Sometimes I like to play with code, this time, when looking around for the ways to apply the memoized function pattern with JavaScript, I found myself with a question:

How to memoize a function using the prototype chain?

I know, I know, the prototype? C’mon, why do this if whe practically don’t even need to, explicitly, mess with that these days?

Well, my answer to that is: knowledge is knowledge, even the simple ones, now let’s get to the code!

First, I declared a constructor function with just one property called “store”:

Well, now that we have our constructor, let’s add a method to its prototype chain, for te sake of simplicity our method will just get a number and multply it by 2, we’ll call it “double”:

And that’s it folks, thank you for your attention!

Just kidding, let me explain whats happening inside this method;

First we have a conditional, we get our store object previously declared inside our constructor, and look into it for a property, the “n” parameter. Since “n’ is a number we have to use curly braces, then, if we have the “n” property on our store, we simply return it, if we don’t, the function continues with the calculations and store our n parameter, for future calls.

Now we just have to instantiate our Memoized function, look at the complete code:

Pretty simple, hun?

That’s it. Thanks for your attention folks ;). Now go play with some kittens, they’re the best (unless you’re allergic to then, in this case, don’t do it).

Tip: You can store virtually anything with the Memoized function, even other functions ;).

Add a comment

Related posts:

Inspect the traffic between VPC to VPC using AWS Network Firewall

AWS Network Firewall is a managed service that makes it easy to deploy essential network protections for all of your Amazon Virtual Private Clouds (VPCs). The service can be setup with just a few…