Is it possible to solve this task using static methods? It is possible not to solve it) it is just interesting. But if there is a desire and time, I will be glad

Create a makeCaching (f) decorator that takes the function f and returns a wrapper that caches its results.

In this problem, the function f has only one argument, and it is a number.

The first time the wrapper is called with a specific argument, it calls f and remembers the value. For the second and subsequent calls with the same argument, the memorized value is returned.

function f(x) { return Math.random()*x; } function makeCaching(f) { var cache = {}; return function(x) { if (!(x in cache)) { cache[x] = f.call(this, x); } return cache[x]; }; } f = makeCaching(f); var a = f(1); var b = f(1); alert( a == b ); // true (значение закешировано) b = f(2); alert( a == b ); // false, другой аргумент => другое значение 
  • f.call(this, x); - ?? - Igor
  • "// true (value is cached)" - a and b are numbers. Kashiruyu, do not kashiruyu, they will still be the same for the same х . - Igor
  • What's wrong here: f.call (this, x) ;? We have one argument if you are about the context of course - ZdraviSmisl
  • why here .call(this ? - Igor
  • one
    I understand each word in this phrase separately - Igor

1 answer 1

 { function f(x) { return x } function makeCaching(_f) { var cache = {} return function (x) { if (!(x in cache)) { cache[x] = [_f(x)] } return cache[x] }; } let f2 = makeCaching(f) var a = f2(1) var b = f2(1) var c = f2(1) console.log(a) //[1] console.log(a === b) // true console.log(b === c) // true console.log(a === [1]) // false } console.log('---') { function f(x) { return x } function makeCaching(_f) { var cache = {} return function (x) { if (!(x in cache)) { cache[x] = _f.call(this, x) } return cache[x] }; } let f2 = makeCaching(f) var a = f2(1) var b = f2(1) var c = f2(1) console.log(a) // 1 console.log(a === b) // true console.log(b === c) // true console.log(a === 1) // true }