Decorators and forwarding, call/apply

Transparent caching

// 有一個很吃資源的函式,可以用一個包裝函式把函式丟進去,同樣參數跑出同樣結果不用重複運算。
function slow(x) {
  // there can be a heavy CPU-intensive job here
  alert(`Called with ${x}`);
  return x;
}

function cachingDecorator(func) {
  let cache = new Map();

  return function(x) {
    if (cache.has(x)) { // if the result is in the map
      return cache.get(x); // return it
    }

    let result = func(x); // otherwise call func

    cache.set(x, result); // and cache (remember) the result
    return result;
  };
}

slow = cachingDecorator(slow);

alert( slow(1) ); // slow(1) is cached
alert( "Again: " + slow(1) ); // the same

alert( slow(2) ); // slow(2) is cached
alert( "Again: " + slow(2) ); // the same as the previous line

// 包裝函數可以重複使用
// 包裝函數是獨立的不影響函數
// 可以使用多個包裝函數

Using “func.call” for the context

Going multi-argument with “func.apply”

Borrowing a method

Last updated

Was this helpful?