alanhe421 / coding-note

note
3 stars 1 forks source link

异步求和 #333

Open alanhe421 opened 3 years ago

alanhe421 commented 3 years ago

提供一个异步 add 方法如下,需要实现一个 await sum(...args) 函数:

function asyncAdd(a, b, callback) {
  setTimeout(function () {
    callback(null, a + b);
  }, 1000);
}

see https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/484

alanhe421 commented 3 years ago
function asyncAdd(a, b, callback) {
  setTimeout(function () {
    callback(null, a + b);
  }, 1000);
}

function add(a, b) {
  return new Promise((resolve) => {
    asyncAdd(a, b, (_, sum) => resolve(sum));
  });
}

function sum(...args) {
  return new Promise((resolve) => {
    args
      .reduce((p, n) => p.then((total) => add(total, n)), Promise.resolve(0))
      .then(resolve);
  });
}

async function main() {
  console.time('sum');
  const res = await sum(11, 2, 3, 4);
  console.log(res);
  console.timeEnd('sum');
}
main();
alanhe421 commented 3 years ago

两两一组提升执行速度

async function sum(...args) {
  if (args.length === 1) return args[0];
  let result = [];
  for (let i = 0; i < args.length - 1; i += 2) {
    result.push(add(args[i], args[i + 1]));
  }
  if (args.length % 2) result.push(args[args.length - 1]);
  return sum(...(await Promise.all(result)));
}