Skip to content

装饰器

纯函数,输入固定,输出固定:

js
function slow(x) {
  return x;
}

对他进行优化,使用缓存保存结果:

js
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;
  };
}

cachingDecorator 是一个 装饰者(decorator):一个特殊的函数,它接受另一个函数并改变它的行为。

decorator 在不影响 原本函数代码的情况下为其增强。