JS Addition

杜绝0.1 + 0.2 =0.30000000000000004 问题;

function add(num1, num2) {
  const num1Digits = (num1.toString().split('.')[1] || '').length;
  const num2Digits = (num2.toString().split('.')[1] || '').length;
  const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
  return (num1 * baseNum + num2 * baseNum) / baseNum;
}

异步求和函数

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

简化:两数之和

function sumT(a, b) {
    return await new Promise((resolve, reject) => {
      asyncAdd(a, b, (err, res) => {
        if(!err) {
          resolve(res)
        }
        reject(err)
      })
    })
  }

const test = await sumT(1, 2)
console.log(test) // 3

加深:多数之和

function sum(...args) {
    return new Promise((resolve) => {
      args.reduce((acc, cur) => acc.then((total) => sumT(total, cur)), Promise.resolve(0)).then(resolve);
    });
}
 console.time('sum');
 await sum(1, 2, 3, 4, 5); // 15
 console.timeEnd('sum');

优化:使用 Promise.all

async function sum(...args) {
    console.log(args); // 用于考察每次迭代的过程
    if (args.length === 1) return args[0];  // 如果仅有一个,直接返回
    let result = [];
    // 两两一组,如果有剩余一个,直接进入
    for (let i = 0; i < args.length - 1; i += 2) {
      result.push(sumT(args[i], args[i + 1]));
    }
    if (args.length % 2) result.push(args[args.length - 1]);
    return sum(...(await Promise.all(result))); // Promise.all 组内求和
} 

test = await sum(1, 2, 3, 4, 5);

Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.A new tool that blends your everyday work apps into one. It's the all-in-one workspace for you and your teamhttps://serious-lose.notion.site/Addition-d55df1e3417147f096855f4977ddf425 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值