-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathstack_queue.js
89 lines (81 loc) · 1.79 KB
/
stack_queue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* @authors : qieguo
* @date : 2016/11/29
* @version : 1.0
* @description : js模拟链表
*/
'use strict';
function pairTest(str) {
var open = {
'<': '>',
'{': '}',
'(': ')',
};
var close = {
'>': '<',
'}': '{',
')': '(',
};
var stack = [];
var result = [];
for (var i = 0, len = str.length; i < len; i++) {
if (open[str[i]]) {
stack.push({index: i, value: str[i]});
}
if (close[str[i]]) {
if (close[str[i]] === stack[stack.length - 1].value) {
var temp = stack.pop();
result.push(str.slice(temp.index + 1, i));
} else {
throw new Error('匹配出错!');
}
}
}
return result;
}
console.log(pairTest('sdf\<asdsdfeesf{sdfefi{esadf{aefw}sdfw}sd}\>'));
/**
* 异步操作池
* @param {Array<Promise>} tasks
* @param {Number} limit 最大并发数,默认为1表示串行
* 两种错误处理:1、其中一个任务出错就停止所有;2、执行完所有任务后收集所有错误
*/
function asyncPoolByThunk(tasks, limit = 1, cb = () => {}, options = {}) {
const stopImmediate = options.stopImmediate;
let index = limit - 1;
let errs = [];
function next(err) {
if (err) {
errs.push(err);
if (stopImmediate) {
cb(errs);
return;
}
}
if (index > tasks.length) {
cb(errs);
return;
}
const current = tasks[++index];
if (typeof current === 'function') {
if (stopImmediate && errs.length > 0) {
return;
}
current(next);
}
}
for (let k = 0; k < limit; k++) {
tasks[k](next);
}
}
function asyncFn(params) {
return function (next) {
setTimeout(() => {
console.log('async', params);
next(params === '4' ? '5555' : null);
}, 1000);
}
}
asyncPoolByThunk('123456789'.split('').map(el => asyncFn(el)), 3, function (errs) {
console.log('errs', errs);
}, { stopImmediate: true });