异步方法并发数量的控制
如有异步方法
function loadAsync(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve("执行" + time)
}, time)
})
}
- reduce+promise执行
function limitLoad(loadFn, url, limitNum) {
let totalUrl = [].concat(url);
let res = [];
let promiseQueue = totalUrl.splice(0, limitNum).map((item, index) => {
return loadFn(item).then(item => {
res.push(item);
return index;
})
})
totalUrl.reduce((last, current, nowIndex) => {
return last.then(() => {
return Promise.race(promiseQueue)
}).then(fastIndex => {
promiseQueue[fastIndex] = loadFn(current).then(item => {
res.push(item);
return nowIndex;
})
})
}, Promise.resolve()).then(() => {
Promise.all(promiseQueue).then(() => {
console.log('异步队列顺序', url)
console.log('执行顺序', res)
})
})
}
- 循环加递归
function limitLoad2(loadFn, url, limitNum) {
return new Promise(resolve => {
const allUrl = url;
const Length = allUrl.length;
const res = [];
let i = 0;
const work = () => {
while (allUrl.length && i < limitNum) {
const useUrl = allUrl[0]
allUrl.splice(0, 1)
loadFn(useUrl).then(data => {
res.push(data);
i--;
if (Length === res.length) {
resolve(res);
}
work();
});
i++;
}
}
work();
})
}
单次订阅发布
class Observer {
constructor() {
this.events_ = {}
}
onceEvent(event, callback) {
var wrapFn = (...args) => {
callback.apply(this, args);
}
this.on(event, wrapFn)
}
on(event, callback) {
var callbacks = this.events_[event] || [];
callbacks.push(callback);
this.events_[event] = callbacks;
return this;
}
emit(...args) {
var event = args[0]
var params = args.slice(1);
var callbacks = this.events_[event]
callbacks.forEach((fn, index) => {
fn.apply(this, params);
callbacks.splice(index, 1);
this.events_[event] = callbacks;
index--;
})
return this;
}
}
var observer = new Observer();
observer.onceEvent("flush", (params) => console.log(params))
observer.emit("flush", "flush111");
observer.emit("flush", "flush222");
异步执行和js隐式转换
实现sum(1,2,3,4,5,6) = 21; sum中调用asyncAdd方法来相加
function asyncAdd(a, b, callback) {
setTimeout(function () {
callback(null, a + b)
}, 1000)
}
- 三种方式实现:
- 直接await (easy)
- 并发执行 (mid)
- js隐式转换 (hard)
async function sum(rest, type) {
// 请在此处完善代码
switch (type) {
case 'easy':
var result = rest.shift()
for (var num of rest) {
// 使用promise 获取相加结果
result = await new Promise(resolve => {
asyncAdd(result, num, (_, res) => {
resolve(res)
})
})
}
// 返回执行结果
return result;
case 'mid':
if (rest.length <= 1) {
return rest[0] || 0
}
var promises = []
// 遍历将数组里面的值两个两个的执行
for (var i = 0; i < rest.length; i += 2) {
promises.push(
new Promise(resolve => {
// 如果 rest[i+1] 是 undefined, 说明数组长度是奇数,这个是最后一个
if (rest[i + 1] === undefined) {
resolve(rest[i])
} else {
// 调用asyncAdd 进行计算
asyncAdd(rest[i], rest[i + 1], (_, result) => {
resolve(result)
})
}
})
)
}
// 获取第一次计算结果
var result = await Promise.all(promises)
// 然后将第一次获取到的结果即 [3,7,11] 再次调用 sum执行
return await sum(...result);
case 'hard':
var result = 0
// 隐氏类型转换, 对象 + 数字,会先调用对象的toString 方法
var obj = {}
obj.toString = function () {
return result
}
var promises = []
for (var num of rest) {
promises.push(new Promise((resolve) => {
asyncAdd(obj, num, (_, res) => {
resolve(res)
})
}).then(res => {
// 在这里将 result的值改变之后,obj.toString 的返回值就变了,这时候下一个setTimeout调用时就使用了新值
result = res
}))
}
await Promise.all(promises)
return result
}
}
消费金额price匹配拥有钞票最少的组合
function dfs_(tickets = [1,2,3,4,5,6,7,8,9], price = 39) {
let tic = tickets.sort((a, b) => a - b).filter(a => a < price);
let splurs = price;
let res = [];
let total = 0;
while (splurs > 0 && !!tic.length) {
let curentUse = 0;
let curentTick = 0;
curentTick = tic[tic.length - 1];
curentUse = Math.floor(splurs / curentTick);
if (curentUse > 0 && curentTick > 0) {
splurs = splurs - curentUse * curentTick;
res.push({
tic: curentTick,
count: curentUse,
})
total += curentUse;
}
if (curentTick) tic.splice(tic.length - 1, 1)
}
return splurs === 0 ? {
total,
res,
} : "fail"
}
实现decodeString(“2[a3[b]]”) = abbbabbb;
function decodeString(str) {
var countStack = [];
var itemStack = [];
var multi = 0;
var res = "";
for (var a = 0; a < str.length; a++) {
const cur = str.charAt(a);
if (cur === "[") {
countStack.push(multi);
itemStack.push(res);
res = "";
multi = 0;
} else if (cur === "]") {
let count = countStack.pop();
let temp = "";
for (var i = 0; i < count; i++) {
temp += res;
}
res = itemStack.pop() + temp;
} else if (cur >= "0" && cur <= "9") {
multi = multi * 10 + (cur - '0');
} else {
console.log(res, multi)
res += cur;
}
}
return res;
}
console.log(decodeString("2[3[a]2[bc]d]"))