JS Addition

 2023-09-10 阅读 20 评论 0

摘要:杜绝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

杜绝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); // 15console.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 

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/41113.html

下一篇:Dart 13-Day

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息