高级前端
js
【Q743】实现 batchFn 函数,可以批量执行函数

实现 batchFn 函数,可以批量执行函数

更多描述 补全及实现一下函数

let executeCount = 0;
const targetFn = async (nums) => {
  executeCount++;
  return nums.map((num) => 2 * num + 1);
};
 
const batcher = (fn) => {
  // todo batch logic
  return () => {};
};
 
const batchedFn = batcher(targetFn);
 
const main = async () => {
  const [result1, result2, result3] = await Promise.all([
    batchedFn([1, 2, 3]),
    batchedFn([4, 5]),
    batchedFn([6, 7]),
  ]);
 
  console.log(result1, result2, result3);
  console.log(executeCount); // 预期为 1
};
 
main();

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 800 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

const batcher = (fn) => {
  // todo batch logic
  let options = [];
  let cache = undefined;
  return async (args) => {
    options = [...options, ...args];
    if (cache) {
      return cache;
    }
    const p = new Promise(async (resolve) => {
      const result = await fn(options);
      const map = result.reduce((acc, x, i) => {
        const v = options[i];
        acc[v] = x;
        return acc;
      }, {});
      resolve(args.map((a) => map[a]));
    });
    cache = p;
    return p;
  };
};