refactor: clone data only when needed

This commit is contained in:
arthurfiorette 2022-03-11 17:02:31 -03:00
parent 3a800d78ea
commit 09a69f8006
No known key found for this signature in database
GPG Key ID: 9D190CD53C53C555

View File

@ -16,6 +16,8 @@ declare const structuredClone: (<T>(value: T) => T) | undefined;
* *
* If you need to modify it's data, you can do by the `data` property. * If you need to modify it's data, you can do by the `data` property.
* *
* @param {boolean} cloneData if the data returned by `find()` should be cloned to avoid mutating the original data outside the `set()` method.
*
* @example * @example
* *
* ```js * ```js
@ -30,11 +32,12 @@ declare const structuredClone: (<T>(value: T) => T) | undefined;
* delete memoryStorage.data[id]; * delete memoryStorage.data[id];
* ``` * ```
*/ */
export function buildMemoryStorage() { export function buildMemoryStorage(cloneData = false) {
const storage = buildStorage({ const storage = buildStorage({
set: (key, value) => { set: (key, value) => {
storage.data[key] = value; storage.data[key] = value;
}, },
remove: (key) => { remove: (key) => {
delete storage.data[key]; delete storage.data[key];
}, },
@ -42,16 +45,16 @@ export function buildMemoryStorage() {
find: (key) => { find: (key) => {
const value = storage.data[key]; const value = storage.data[key];
if (value === undefined) { if (cloneData && value !== undefined) {
return value; /* istanbul ignore if 'only available on super recent browsers' */
if (typeof structuredClone === 'function') {
return structuredClone(value);
}
return JSON.parse(JSON.stringify(value)) as StorageValue;
} }
/* istanbul ignore if 'only available on super recent browsers' */ return value;
if (typeof structuredClone === 'function') {
return structuredClone(value);
}
return JSON.parse(JSON.stringify(value)) as StorageValue;
} }
}) as MemoryStorage; }) as MemoryStorage;