Skip to content

Commit c594a6a

Browse files
optimize StorageAdapter using an internal keys array and cache object
1 parent a7d3246 commit c594a6a

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

src/storages/inLocalStorage/storageAdapter.ts

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,13 @@ function isTillKey(key: string) {
99

1010
export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.StorageWrapper): Required<StorageAdapter> {
1111
let keys: string[] = [];
12-
let values: string[] = [];
12+
let cache: Record<string, string> = {};
1313

1414
let loadPromise: Promise<void> | undefined;
1515
let savePromise = Promise.resolve();
1616

1717
function _save() {
1818
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>);
2319
return Promise.resolve(wrapper.setItem(prefix, JSON.stringify(cache)));
2420
}).catch((e) => {
2521
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
3127
return loadPromise || (loadPromise = Promise.resolve().then(() => {
3228
return wrapper.getItem(prefix);
3329
}).then((storedCache) => {
34-
const cache = JSON.parse(storedCache || '{}');
30+
cache = JSON.parse(storedCache || '{}');
3531
keys = Object.keys(cache);
36-
values = keys.map(key => cache[key]);
3732
}).catch((e) => {
3833
log.error(LOG_PREFIX + 'Rejected promise calling wrapper `getItem` method, with error: ' + e);
3934
}));
@@ -46,9 +41,7 @@ export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.St
4641
return keys.length;
4742
},
4843
getItem(key: string) {
49-
const index = keys.indexOf(key);
50-
if (index === -1) return null;
51-
return values[index];
44+
return cache[key] || null;
5245
},
5346
key(index: number) {
5447
return keys[index] || null;
@@ -57,14 +50,13 @@ export function storageAdapter(log: ILogger, prefix: string, wrapper: SplitIO.St
5750
const index = keys.indexOf(key);
5851
if (index === -1) return;
5952
keys.splice(index, 1);
60-
values.splice(index, 1);
53+
delete cache[key];
6154

6255
if (isTillKey(key)) _save();
6356
},
6457
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;
6860

6961
if (isTillKey(key)) _save();
7062
}

0 commit comments

Comments
 (0)