Просмотр исходного кода

Merge pull request #2183 from tgeorgiev/cache-fix

Cache fixes
Evan You 10 лет назад
Родитель
Сommit
a17ab47cfe
2 измененных файлов с 45 добавлено и 14 удалено
  1. 21 14
      src/cache.js
  2. 24 0
      test/unit/specs/cache_spec.js

+ 21 - 14
src/cache.js

@@ -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
 }
 
 /**
@@ -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
 }

+ 24 - 0
test/unit/specs/cache_spec.js

@@ -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)
@@ -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')
+  })
 })