How does the decorator work?



  • function slow(x) {
      alert(`Called with ${x}`);
      return x;
    }
    
    function cachingDecorator(func) {
      let cache = new Map();
    
      return function(x) {
        if (cache.has(x)) { 
          return cache.get(x);
        }
    
        let result = func(x);
    
        cache.set(x, result);
        return result;
      };
    }
    
    slow = cachingDecorator(slow); // *
    
    alert( slow(1) ); // slow(1)
    alert( "Again: " + slow(1) );
    

    How does that work? We keep it. cachingDecorator(slow) to the variable slow we have a function. The function#1 was placed in another function#2 and thus assigned everything to function #1.

    If there are sources where it's more clearly explained, please.



  • cachingDecorator() - creates a lock, i.e. a combination of the function transferred to it and areas of visibility attached to that function.

    In this case, method cachingDecorator() (to avoid confusion) returns an anonymous function that has access to the following data:

    • transferred to cachingDecorator() functionslow())
    • vocabulary for anonymous functioncache = Map())

    The vocabulary records the functional challenges slow♪ As a key, the parameter with which it is caused is recorded. And as a matter of importance, returned data.

    So the anonymous function of "memorizes" its challenges. If she's repeating the same parameter, she's just returning the data from the kash without renouncing the function. slow()

    Expression cachingDecorator(slow) creates a sort of kashing shell over a function. slow()♪ The inside of this casing will be caused by the function slow() Only if it wasn't called for the same parameter.

    Expression slow = cachingDecorator(slow) redefines the variable slow - by assigning her a new role-boat. To make it easier to understand this transformation, a function can be declared slow() Renumber as follows:

    var slow = function(x){return x}; // alert я убрал
    

    It's an almost equivalent expression. function slow(x){return x}♪ As a result, we declare a variable slow and give her an object-function. This function can be triggered by round brackets, transmitting the necessary parameters inside. Still.

    Therefore, in terms slow = cachingDecorator(slow) We have a different function in the same variable, but that keeps knowledge of the former function and has access to the dictionary of her challenges.

    // slow() - простая функция, возвращающая переданный в нее аргумент как есть.
    

    function slow(x) {
    return x;
    }

    // cachingDecorator() - функция, принимающая в качестве параметра другую функцию как объект
    // создает замыкание для переданной функции (сохраняемую индивидуальную область видимости)
    // возвращает анонимную функцию, имеющую доступ к данным вмещающей ее функции

    function cachingDecorator(func) {
    let cache = new Map(); // "Словарь" для хранения данных замыкания

    // анонимная (безымянная функция), принимающая один аргумент - x
    

    return function(x) {
    if (cache.has(x)) { // Если в словаре есть ключ == x
    return cache.get(x); // Возвращаем значение под этим ключом
    }
    // Иначе вызываем, переданную в cachingDecorator, функцию.
    // Возваращенный результат присваиваем переменной result
    let result = func(x);

    cache.set(x, result); // Записываем данные в cache под ключом x
    return result;        // Возвращаем результат
    

    };
    }

    // Переопределяем переменную slow
    // Теперь она содержит результат вызова cachingDecorator(slow)
    // т.е. она хранит функцию, имеющую доступ к пустому словарю и объекту-функции slow()
    slow = cachingDecorator(slow);

    // Первый вызов новой функции с параметром 1
    // В словаре ключа 1 нет -> вызываем функцию (== slow(1))
    // Возвращаемое значение (1) записываем в словарь под ключом 1
    console.log( slow(1));

    // Повторный вызов функции с параметром 1
    // В словаре содержится ключ 1
    // Возвращаем значение из словаря под ключом 1 - 1
    console.log( "Again: " + slow(1) );


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2