foreach.js
2.29 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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
var test = require('tap').test
var LRU = require('../')
test('forEach', function (t) {
var l = new LRU(5)
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
var i = 9
l.forEach(function (val, key, cache) {
t.equal(cache, l)
t.equal(key, i.toString())
t.equal(val, i.toString(2))
i -= 1
})
// get in order of most recently used
l.get(6)
l.get(8)
var order = [ 8, 6, 9, 7, 5 ]
var i = 0
l.forEach(function (val, key, cache) {
var j = order[i ++]
t.equal(cache, l)
t.equal(key, j.toString())
t.equal(val, j.toString(2))
})
t.equal(i, order.length);
t.end()
})
test('keys() and values()', function (t) {
var l = new LRU(5)
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
t.similar(l.keys(), ['9', '8', '7', '6', '5'])
t.similar(l.values(), ['1001', '1000', '111', '110', '101'])
// get in order of most recently used
l.get(6)
l.get(8)
t.similar(l.keys(), ['8', '6', '9', '7', '5'])
t.similar(l.values(), ['1000', '110', '1001', '111', '101'])
t.end()
})
test('all entries are iterated over', function(t) {
var l = new LRU(5)
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
var i = 0
l.forEach(function (val, key, cache) {
if (i > 0) {
cache.del(key)
}
i += 1
})
t.equal(i, 5)
t.equal(l.keys().length, 1)
t.end()
})
test('all stale entries are removed', function(t) {
var l = new LRU({ max: 5, maxAge: -5, stale: true })
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
var i = 0
l.forEach(function () {
i += 1
})
t.equal(i, 5)
t.equal(l.keys().length, 0)
t.end()
})
test('expires', function (t) {
var l = new LRU({
max: 10,
maxAge: 50
})
for (var i = 0; i < 10; i++) {
l.set(i.toString(), i.toString(2), ((i % 2) ? 25 : undefined))
}
var i = 0
var order = [ 8, 6, 4, 2, 0 ]
setTimeout(function () {
l.forEach(function (val, key, cache) {
var j = order[i++]
t.equal(cache, l)
t.equal(key, j.toString())
t.equal(val, j.toString(2))
})
t.equal(i, order.length);
setTimeout(function () {
var count = 0;
l.forEach(function (val, key, cache) { count++; })
t.equal(0, count);
t.end()
}, 25)
}, 26)
})