Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 21 additions & 14 deletions src/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,29 @@ var p = Cache.prototype
*/

p.put = function (key, value) {
var entry = {
key: key,
value: value
}
this._keymap[key] = entry
if (this.tail) {
this.tail.newer = entry
entry.older = this.tail
} else {
this.head = entry
}
this.tail = entry
var removed
if (this.size === this.limit) {
return this.shift()
} else {
removed = this.shift()
}

var entry = this.get(key, true)
if (!entry) {
entry = {
key: key
}
this._keymap[key] = entry
if (this.tail) {
this.tail.newer = entry
entry.older = this.tail
} else {
this.head = entry
}
this.tail = entry
this.size++
}
entry.value = value

return removed
}

/**
Expand All @@ -64,6 +70,7 @@ p.shift = function () {
this.head.older = undefined
entry.newer = entry.older = undefined
this._keymap[entry.key] = undefined
this.size--
}
return entry
}
Expand Down
24 changes: 24 additions & 0 deletions test/unit/specs/cache_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ describe('Cache', function () {
expect(toString(c)).toBe('adam:29 < john:26 < angela:24 < bob:48')
})

it('put with same key', function () {
var same = new Cache(4)
same.put('john', 29)
same.put('john', 26)
same.put('john', 24)
same.put('john', 48)
expect(same.size).toBe(1)
expect(toString(same)).toBe('john:48')
})

it('get', function () {
expect(c.get('adam')).toBe(29)
expect(c.get('john')).toBe(26)
Expand All @@ -50,4 +60,18 @@ describe('Cache', function () {
expect(toString(c)).toBe('john:26 < bob:48 < angela:24 < ygwie:81')
expect(c.get('adam')).toBeUndefined()
})

it('shift', function () {
var shift = new Cache(4)
shift.put('adam', 29)
shift.put('john', 26)
shift.put('angela', 24)
shift.put('bob', 48)

shift.shift()
shift.shift()
shift.shift()
expect(shift.size).toBe(1)
expect(toString(shift)).toBe('bob:48')
})
})