File tree Expand file tree Collapse file tree 2 files changed +45
-14
lines changed Expand file tree Collapse file tree 2 files changed +45
-14
lines changed Original file line number Diff line number Diff line change @@ -32,23 +32,29 @@ var p = Cache.prototype
3232 */
3333
3434p . put = function ( key , value ) {
35- var entry = {
36- key : key ,
37- value : value
38- }
39- this . _keymap [ key ] = entry
40- if ( this . tail ) {
41- this . tail . newer = entry
42- entry . older = this . tail
43- } else {
44- this . head = entry
45- }
46- this . tail = entry
35+ var removed
4736 if ( this . size === this . limit ) {
48- return this . shift ( )
49- } else {
37+ removed = this . shift ( )
38+ }
39+
40+ var entry = this . get ( key , true )
41+ if ( ! entry ) {
42+ entry = {
43+ key : key
44+ }
45+ this . _keymap [ key ] = entry
46+ if ( this . tail ) {
47+ this . tail . newer = entry
48+ entry . older = this . tail
49+ } else {
50+ this . head = entry
51+ }
52+ this . tail = entry
5053 this . size ++
5154 }
55+ entry . value = value
56+
57+ return removed
5258}
5359
5460/**
@@ -64,6 +70,7 @@ p.shift = function () {
6470 this . head . older = undefined
6571 entry . newer = entry . older = undefined
6672 this . _keymap [ entry . key ] = undefined
73+ this . size --
6774 }
6875 return entry
6976}
Original file line number Diff line number Diff line change @@ -32,6 +32,16 @@ describe('Cache', function () {
3232 expect ( toString ( c ) ) . toBe ( 'adam:29 < john:26 < angela:24 < bob:48' )
3333 } )
3434
35+ it ( 'put with same key' , function ( ) {
36+ var same = new Cache ( 4 )
37+ same . put ( 'john' , 29 )
38+ same . put ( 'john' , 26 )
39+ same . put ( 'john' , 24 )
40+ same . put ( 'john' , 48 )
41+ expect ( same . size ) . toBe ( 1 )
42+ expect ( toString ( same ) ) . toBe ( 'john:48' )
43+ } )
44+
3545 it ( 'get' , function ( ) {
3646 expect ( c . get ( 'adam' ) ) . toBe ( 29 )
3747 expect ( c . get ( 'john' ) ) . toBe ( 26 )
@@ -50,4 +60,18 @@ describe('Cache', function () {
5060 expect ( toString ( c ) ) . toBe ( 'john:26 < bob:48 < angela:24 < ygwie:81' )
5161 expect ( c . get ( 'adam' ) ) . toBeUndefined ( )
5262 } )
63+
64+ it ( 'shift' , function ( ) {
65+ var shift = new Cache ( 4 )
66+ shift . put ( 'adam' , 29 )
67+ shift . put ( 'john' , 26 )
68+ shift . put ( 'angela' , 24 )
69+ shift . put ( 'bob' , 48 )
70+
71+ shift . shift ( )
72+ shift . shift ( )
73+ shift . shift ( )
74+ expect ( shift . size ) . toBe ( 1 )
75+ expect ( toString ( shift ) ) . toBe ( 'bob:48' )
76+ } )
5377} )
You can’t perform that action at this time.
0 commit comments