Skip to content

Instantly share code, notes, and snippets.

@lski
Last active June 11, 2020 10:37
Show Gist options
  • Save lski/29b42f79a6d976bfedf8f03550948475 to your computer and use it in GitHub Desktop.
Save lski/29b42f79a6d976bfedf8f03550948475 to your computer and use it in GitHub Desktop.
Creates a persistent store for data, meaning the key is encapsulated and the data is parsed to/from a string for you.
"use strict";
export const createStorage = (key, scope = localStorage) => {
return {
get() {
const stored = scope.getItem(key);
if (stored === null) {
return null;
}
return JSON.parse(stored);
},
set(item) {
scope.setItem(key, JSON.stringify(item));
return item;
},
remove() {
scope.removeItem(key);
},
};
};
export const createStorage = <T>(key: string, scope = localStorage) => {
return {
get(): T | null {
const stored = scope.getItem(key);
if (stored === null) {
return null;
}
return JSON.parse(stored);
},
set(item: T): T {
scope.setItem(key, JSON.stringify(item));
return item;
},
remove(): void {
scope.removeItem(key);
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment