/
log.js
61 lines (55 loc) · 1.58 KB
/
log.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
class Log {
static equal (left, right) {
return left.length == right.length &&
left.every((element, index) => element == right[index])
}
static startsWith (array, startsWith) {
return array.length <= startsWith &&
startsWith.every((element, index) => element == array[index])
}
constructor (max) {
this.size = 0
this.length = 0
this.max = max
this.head = { event: null, next: null, previous: null, index: -1 }
this.head.next = this.head.previous = this.head
}
get index () {
return this.length - 1
}
add (event) {
const node = {
index: this.length++,
event: event,
previous: this.head.previous,
next: this.head
}
node.next.previous = node
node.previous.next = node
if (++this.size > this.max) {
const remove = this.head.next
remove.next.previous = remove.previous
remove.previous.next = remove.next
this.size--
}
return event
}
find (index, f) {
const found = []
if (index < this.head.next.index) {
return null
}
let iterator = this.head.next
while (iterator !== this.head && iterator.index != index) {
iterator = iterator.next
}
while (iterator != this.head) {
if (f(iterator.event)) {
found.push(iterator.event)
}
iterator = iterator.next
}
return found
}
}
module.exports = Log