Skip to main content

其他

异步加法

参考 https://juejin.cn/post/7134583899597832200?share_token=f60dd2f4-aab2-4adb-aaef-83209f3d608a

function asyncAdd(a, b, cb) {
setTimeout(() => {
cb(null, a + b);
}, Math.random() * 1000);
}

async function total() {
const res1 = await sum(1, 2, 3, 4, 5, 6, 4);
const res2 = await sum(1, 2, 3, 4, 5, 6, 4);
return [res1, res2];
}

total();

// 实现下 sum 函数。注意不能使用加法,在 sum 中借助 asyncAdd 完成加法。尽可能的优化这个方法的时间。
const cash: any = {};

function isUndefined(target: any) {
return target === void 0;
}

async function sum(...nums: number[]) {
let res: any = 0;
const key = nums.join("+");

if (!isUndefined(cash[key])) return cash[key];

for (const n of nums) {
res = await caculate(res, n);
}
cash[key] = res;
return res;
}

function caculate(num1: number, num2: number) {
return new Promise((resolve, reject) => {
asyncAdd(num1, num2, (err: any, rs: number) => {
if (err) {
reject(err);
return;
}
resolve(rs);
});
});
}

如何进一步优化?

  • Promise.all,并行计算

版本号排序

有一组版本号如下['0.1.1', '2.3.3', '0.302.1', '4.2', '4.3.5', '4.3.4.5']。 现在需要对其进行排序,排序的结果为 ['4.3.5','4.3.4.5','2.3.3','0.302.1','0.1.1']

arr.sort((a, b) => {
let i = 0;
const arr1 = a.split(".");
const arr2 = b.split(".");
while (true) {
const s1 = arr1[i];
const s2 = arr2[i];
i++;
if (s1 === undefined || s2 === undefined) {
return arr2.length - arr1.length;
}
if (s1 === s2) continue;
return s2 - s1;
}
});
console.log(arr);

参考 https://github.com/hengg/js-walker/issues/9

LazyMan

实现一个 LazyMan,可以按照以下方式调用:

LazyMan(“Hank”)
// 输出
Hi! This is Hank!

LazyMan(“Hank”).sleep(10).eat(“dinner”)
// 输出
Hi! This is Hank!
// 等待10秒
Wake up after 10
Eat dinner~

LazyMan(“Hank”).eat(“dinner”).eat(“supper”)
// 输出
Hi This is Hank!
Eat dinner~
Eat supper~

LazyMan(“Hank”).eat(“supper”).sleepFirst(5)
// 输出
// 等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
class _LazyMan {
constructor(name) {
this.taskQueue = [];
this.name = name;
this.timer = null;
this.sayHi();
}
next() {
clearTimeout(this.timer);
this.timer = setTimeout(async () => {
for (let i = 0; i < this.taskQueue.length; i++) {
await this.taskQueue[i]();
}
});
return this;
}
sayHi() {
this.taskQueue.push(() => {
console.log("Hi! This is " + this.name);
});
return this.next();
}
eat(str) {
this.taskQueue.push(() => {
console.log("Eat " + str);
});
return this.next();
}
beforSleep(time) {
this.taskQueue.unshift(() => this.sleepPromise(time));
return this.next();
}
sleep(time) {
this.taskQueue.push(() => this.sleepPromise(time));
return this.next();
}
sleepPromise(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("wake up after " + time);
resolve();
}, time * 1000);
});
}
}

function LazyMan(name) {
return new _LazyMan(name);
}

LazyMan("Hank");
LazyMan("Hank").sleep(10).eat("dinner");