Skip to content

Commit 0d0658f

Browse files
authored
Merge pull request #7 from Kikobeats/queue
perf: avoid array.shift, use a linked list
2 parents 8e01925 + 640880a commit 0d0658f

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@
8080
"@commitlint/config-conventional"
8181
],
8282
"rules": {
83-
"body-max-length": [
83+
"body-max-line-length": [
8484
0
8585
]
8686
}

src/create.js

+31-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,39 @@
11
'use strict'
22

3+
class Node {
4+
constructor (data) {
5+
this.data = data
6+
}
7+
}
8+
9+
class LinkedList {
10+
enqueue (data) {
11+
if (!this.head) {
12+
this.head = new Node(data)
13+
} else {
14+
let current = this.head
15+
while (current.next) {
16+
current = current.next
17+
}
18+
current.next = new Node(data)
19+
}
20+
}
21+
22+
dequeue () {
23+
if (!this.head) return
24+
const data = this.head.data
25+
this.head = this.head.next
26+
return data
27+
}
28+
}
29+
330
module.exports = (slots = 1) => {
4-
const queue = []
31+
const queue = new LinkedList()
532

633
const release = () => {
734
++slots
8-
if (queue.length > 0) queue.shift()()
35+
const fn = queue.dequeue()
36+
if (fn !== undefined) fn()
937
}
1038

1139
const acquire = resolve => {
@@ -15,9 +43,7 @@ module.exports = (slots = 1) => {
1543

1644
const lock = () =>
1745
new Promise(resolve =>
18-
lock.isLocked()
19-
? queue.push(acquire.bind(null, resolve))
20-
: acquire(resolve)
46+
lock.isLocked() ? queue.enqueue(() => acquire(resolve)) : acquire(resolve)
2147
)
2248

2349
lock.isLocked = () => slots === 0

0 commit comments

Comments
 (0)