如何实现方法链接

时间:2019-05-31 14:59:16

标签: javascript methods method-chaining

是否有一种方法可以链接来自Cache类的以下方法

cache = cache.getKey(key) || cache.setKey(key).get(key); // cache = cache.getKey(key) || cache.setKey(key).getKey(key);

我知道我们有本机方法Map.prototype​.set()Map.prototype​.get(),但我想用这种方法来实现。如果您有任何建议,请告诉我。

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  setKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    return map.set(key, new Cache());
  }

  getKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    return map.get(key);
  }
}

function getCache(args, cache) {
  for (const key of args) {
    cache = cache.getKey(key) || cache.setKey(key).get(key);
    // cache = cache.getKey(key) || cache.setKey(key).getKey(key);
  }
  return cache;
}

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    const item = getCache(args, cache);

    if (Reflect.has(item, 'value')) {
      return item.value;
    }

    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

不幸的是,如果您试图“获取”钥匙,则您无法返回地图,因为您要输入钥匙,因此它必须返回钥匙。因此,您不能链接该方法。但是任何默认情况下都不应该返回内容的方法(IE将是无效的),我们可以这样做:

  

cache = cache.getKey(key)|| cache.setKey(key).get(key);

这将返回布尔值,如||。符号表示如果任一值为true,则返回true。

但是,如果您想像JQuery那样进行链接,那很容易实现!您要做的就是在每个方法中返回this或对象。

像这样:

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  setKey(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    map.set(key, new Cache());
    return this; // HERE'S THE IMPORTANT PART
  }
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3