异步加法

本文最后更新于:6 个月前

实现下sum函数。注意不能使用加法,在sum中借助asyncAdd完成加法。尽可能的优化这个方法的时间。

function asyncAdd(a, b, cb) {
  setTimeout(() => {
    cb(null, a + b);
  }, Math.random() * 1000);
}
async function total() {
  console.time("1");
  const res1 = await sum2(1, 2, 3, 4, 5, 6, 4);
  const res2 = await sum2(1, 2, 3, 4, 5, 6, 4);
  return [res1, res2];
}
total().then((res) => {
  console.timeEnd("1");
  console.log(res);
});
// 实现下sum函数。注意不能使用加法,在sum中借助asyncAdd完成加法。尽可能的优化这个方法的时间。
function sum() {
  let args = Array.prototype.slice.call(arguments);
  let promises = [],
    i = 0;
  for (i; i < args.length; i += 2) {
    promises.push(
      new Promise((r, j) => {
        asyncAdd(args[i], args[i + 1] ?? 0, function () {
          r(arguments[1]);
        });
      })
    );
  }
  return Promise.all(promises).then((res) => {
    if (res.length < 2) return res[0];
    else return sum(...res);
  });
}

function sum2() {
  let args = Array.prototype.slice.call(arguments);
  return args.reduce((pre, cur) => {
    return pre.then(
      (d) => new Promise((r, j) => asyncAdd(d, cur, (a, b) => r(b)))
    );
  }, Promise.resolve(0));
}

假设本地机器无法做加减乘除法,需要通过远程请求让服务端来实现。
以加法为例,现有远程API的模拟实现

const addRemote = async (a, b) =>
  new Promise((resolve) => {
    setTimeout(() => resolve(a + b), 1000);
  });

// 请实现本地的add方法,调用addRemote,能最优的实现输入数字的加法。
async function add(...inputs) {
  // 你的实现
  return inputs.reduce(async (pre, cur) => {
    return pre.then((d) => addRemote(d, cur));
  }, Promise.resolve(0));
}

// 请用示例验证运行结果:
add(1, 2).then((result) => {
  console.log(result); // 3
});

add(3, 5, 2).then((result) => {
  console.log(result); // 10
});

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!