File tree 2 files changed +45
-14
lines changed 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
32
32
*/
33
33
34
34
p . 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
47
36
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
50
53
this . size ++
51
54
}
55
+ entry . value = value
56
+
57
+ return removed
52
58
}
53
59
54
60
/**
@@ -64,6 +70,7 @@ p.shift = function () {
64
70
this . head . older = undefined
65
71
entry . newer = entry . older = undefined
66
72
this . _keymap [ entry . key ] = undefined
73
+ this . size --
67
74
}
68
75
return entry
69
76
}
Original file line number Diff line number Diff line change @@ -32,6 +32,16 @@ describe('Cache', function () {
32
32
expect ( toString ( c ) ) . toBe ( 'adam:29 < john:26 < angela:24 < bob:48' )
33
33
} )
34
34
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
+
35
45
it ( 'get' , function ( ) {
36
46
expect ( c . get ( 'adam' ) ) . toBe ( 29 )
37
47
expect ( c . get ( 'john' ) ) . toBe ( 26 )
@@ -50,4 +60,18 @@ describe('Cache', function () {
50
60
expect ( toString ( c ) ) . toBe ( 'john:26 < bob:48 < angela:24 < ygwie:81' )
51
61
expect ( c . get ( 'adam' ) ) . toBeUndefined ( )
52
62
} )
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
+ } )
53
77
} )
You can’t perform that action at this time.
0 commit comments