@@ -8,13 +8,18 @@ function isTillKey(key: string) {
88}
99
1010export function storageAdapter ( log : ILogger , prefix : string , wrapper : SplitIO . StorageWrapper ) : StorageAdapter {
11- let cache : Record < string , string > = { } ;
11+ let keys : string [ ] = [ ] ;
12+ let values : string [ ] = [ ] ;
1213
1314 let loadPromise : Promise < void > | undefined ;
1415 let savePromise = Promise . resolve ( ) ;
1516
1617 function _save ( ) {
1718 return savePromise = savePromise . then ( ( ) => {
19+ const cache = keys . reduce ( ( acc , key , index ) => {
20+ acc [ key ] = values [ index ] ;
21+ return acc ;
22+ } , { } as Record < string , string > ) ;
1823 return Promise . resolve ( wrapper . setItem ( prefix , JSON . stringify ( cache ) ) ) ;
1924 } ) . catch ( ( e ) => {
2025 log . error ( LOG_PREFIX + 'Rejected promise calling wrapper `setItem` method, with error: ' + e ) ;
@@ -26,7 +31,9 @@ export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.St
2631 return loadPromise || ( loadPromise = Promise . resolve ( ) . then ( ( ) => {
2732 return wrapper . getItem ( prefix ) ;
2833 } ) . then ( ( storedCache ) => {
29- cache = JSON . parse ( storedCache || '{}' ) ;
34+ const cache = JSON . parse ( storedCache || '{}' ) ;
35+ keys = Object . keys ( cache ) ;
36+ values = keys . map ( key => cache [ key ] ) ;
3037 } ) . catch ( ( e ) => {
3138 log . error ( LOG_PREFIX + 'Rejected promise calling wrapper `getItem` method, with error: ' + e ) ;
3239 } ) ) ;
@@ -36,20 +43,29 @@ export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.St
3643 } ,
3744
3845 get length ( ) {
39- return Object . keys ( cache ) . length ;
46+ return keys . length ;
4047 } ,
4148 getItem ( key : string ) {
42- return cache [ key ] || null ;
49+ const index = keys . indexOf ( key ) ;
50+ if ( index === - 1 ) return null ;
51+ return values [ index ] ;
4352 } ,
4453 key ( index : number ) {
45- return Object . keys ( cache ) [ index ] || null ;
54+ return keys [ index ] || null ;
4655 } ,
4756 removeItem ( key : string ) {
48- delete cache [ key ] ;
57+ const index = keys . indexOf ( key ) ;
58+ if ( index === - 1 ) return ;
59+ keys . splice ( index , 1 ) ;
60+ values . splice ( index , 1 ) ;
61+
4962 if ( isTillKey ( key ) ) _save ( ) ;
5063 } ,
5164 setItem ( key : string , value : string ) {
52- cache [ key ] = value ;
65+ let index = keys . indexOf ( key ) ;
66+ if ( index === - 1 ) index = keys . push ( key ) - 1 ;
67+ values [ index ] = value ;
68+
5369 if ( isTillKey ( key ) ) _save ( ) ;
5470 }
5571 } ;
0 commit comments