@@ -9,17 +9,13 @@ function isTillKey(key: string) {
9
9
10
10
export function storageAdapter ( log : ILogger , prefix : string , wrapper : SplitIO . StorageWrapper ) : Required < StorageAdapter > {
11
11
let keys : string [ ] = [ ] ;
12
- let values : string [ ] = [ ] ;
12
+ let cache : Record < string , string > = { } ;
13
13
14
14
let loadPromise : Promise < void > | undefined ;
15
15
let savePromise = Promise . resolve ( ) ;
16
16
17
17
function _save ( ) {
18
18
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 > ) ;
23
19
return Promise . resolve ( wrapper . setItem ( prefix , JSON . stringify ( cache ) ) ) ;
24
20
} ) . catch ( ( e ) => {
25
21
log . error ( LOG_PREFIX + 'Rejected promise calling wrapper `setItem` method, with error: ' + e ) ;
@@ -31,9 +27,8 @@ export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.St
31
27
return loadPromise || ( loadPromise = Promise . resolve ( ) . then ( ( ) => {
32
28
return wrapper . getItem ( prefix ) ;
33
29
} ) . then ( ( storedCache ) => {
34
- const cache = JSON . parse ( storedCache || '{}' ) ;
30
+ cache = JSON . parse ( storedCache || '{}' ) ;
35
31
keys = Object . keys ( cache ) ;
36
- values = keys . map ( key => cache [ key ] ) ;
37
32
} ) . catch ( ( e ) => {
38
33
log . error ( LOG_PREFIX + 'Rejected promise calling wrapper `getItem` method, with error: ' + e ) ;
39
34
} ) ) ;
@@ -46,9 +41,7 @@ export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.St
46
41
return keys . length ;
47
42
} ,
48
43
getItem ( key : string ) {
49
- const index = keys . indexOf ( key ) ;
50
- if ( index === - 1 ) return null ;
51
- return values [ index ] ;
44
+ return cache [ key ] || null ;
52
45
} ,
53
46
key ( index : number ) {
54
47
return keys [ index ] || null ;
@@ -57,14 +50,13 @@ export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.St
57
50
const index = keys . indexOf ( key ) ;
58
51
if ( index === - 1 ) return ;
59
52
keys . splice ( index , 1 ) ;
60
- values . splice ( index , 1 ) ;
53
+ delete cache [ key ] ;
61
54
62
55
if ( isTillKey ( key ) ) _save ( ) ;
63
56
} ,
64
57
setItem ( key : string , value : string ) {
65
- let index = keys . indexOf ( key ) ;
66
- if ( index === - 1 ) index = keys . push ( key ) - 1 ;
67
- values [ index ] = value ;
58
+ if ( keys . indexOf ( key ) === - 1 ) keys . push ( key ) ;
59
+ cache [ key ] = value ;
68
60
69
61
if ( isTillKey ( key ) ) _save ( ) ;
70
62
}
0 commit comments