-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock.ts
More file actions
43 lines (39 loc) · 1.4 KB
/
lock.ts
File metadata and controls
43 lines (39 loc) · 1.4 KB
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
export default class {
processKeyList:string[];
waitingList:{ key: string, resolve:(value:unknown) => any }[];
maxProcessing:number;
constructor(props:{maxProcessing: number} = {maxProcessing: 99999} ) {
this.processKeyList = [];
this.waitingList = [];
this.maxProcessing = props.maxProcessing;
}
public lock = async(key: string) => {
return new Promise((resolve) =>{
if (this.processKeyList.includes(key) || this.processKeyList.length >= this.maxProcessing) {
// 加入列隊,等候可以開始通知
this.waitingList.push( { key: key, resolve: resolve } );
} else {
// 開始現時的工作
this.processKeyList.push(key);
resolve(true);
}
})
}
public unlock = (key: string) => {
// 完成現在的工作
let delIndex = this.processKeyList.indexOf(key);
if (delIndex !== -1) {
this.processKeyList.splice(delIndex, 1);
}
// 尋找下一個工作通知執行
let startProcessingIndex = this.waitingList.findIndex((item) => {
return !this.processKeyList.includes(item.key);
});
if (startProcessingIndex !== -1 && this.processKeyList.length < this.maxProcessing) {
let startProcessing = this.waitingList[startProcessingIndex];
this.waitingList.splice(startProcessingIndex, 1);
this.processKeyList.push(startProcessing.key);
startProcessing.resolve(true);
}
}
}