Skip to content

Commit c5f4925

Browse files
authored
fix(LruObject): do not bumb entry if there is only one entry (#33)
1 parent 0318bb4 commit c5f4925

4 files changed

Lines changed: 64 additions & 0 deletions

File tree

src/LruMap.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ export class LruMap {
2020
}
2121

2222
bumpLru(item) {
23+
if (this.last === item) {
24+
return // Item is already the last one, no need to bump
25+
}
26+
2327
const last = this.last
2428
const next = item.next
2529
const prev = item.prev

src/LruObject.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ export class LruObject {
1717
}
1818

1919
bumpLru(item) {
20+
if (this.last === item) {
21+
return // Item is already the last one, no need to bump
22+
}
23+
2024
const last = this.last
2125
const next = item.next
2226
const prev = item.prev

test/LruMap.spec.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,34 @@ describe('LruMap', function () {
8282
expect(item2Pre).toBe(items[2])
8383
expect(item2Post).toBe(items[2])
8484
})
85+
86+
it('does not overwrite cache.first', async () => {
87+
cache = new LruMap(5, 500)
88+
89+
const key = '10.0.0.1'
90+
const value = 100
91+
92+
cache.set(key, value)
93+
expect(cache.first).not.toBeNull()
94+
95+
cache.get(key)
96+
expect(cache.first).not.toBeNull()
97+
})
98+
99+
it('does not cause TypeError when reaching the cache limit', async () => {
100+
const maxCacheSize = 3
101+
cache = new LruMap(maxCacheSize, 500)
102+
103+
const key = '10.0.0.1'
104+
const value = 100
105+
106+
cache.set(key, value)
107+
cache.get(key)
108+
109+
for (let i = 0; i < maxCacheSize; i++) {
110+
cache.set(i, i)
111+
}
112+
})
85113
})
86114

87115
describe('getMany', () => {

test/LruObject.spec.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,34 @@ describe('LruObject', function () {
8282
expect(item2Pre).toBe(items[2])
8383
expect(item2Post).toBe(items[2])
8484
})
85+
86+
it('does not overwrite cache.first', async () => {
87+
cache = new LruObject(5, 500)
88+
89+
const key = '10.0.0.1'
90+
const value = 100
91+
92+
cache.set(key, value)
93+
expect(cache.first).not.toBeNull()
94+
95+
cache.get(key)
96+
expect(cache.first).not.toBeNull()
97+
})
98+
99+
it('does not cause TypeError when reaching the cache limit', async () => {
100+
const maxCacheSize = 3
101+
cache = new LruObject(maxCacheSize, 500)
102+
103+
const key = '10.0.0.1'
104+
const value = 100
105+
106+
cache.set(key, value)
107+
cache.get(key)
108+
109+
for (let i = 0; i < maxCacheSize; i++) {
110+
cache.set(i, i)
111+
}
112+
})
85113
})
86114

87115
describe('getMany', () => {

0 commit comments

Comments
 (0)