杜绝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