kontra
Version:
Kontra HTML5 game development library
48 lines (44 loc) • 1.35 kB
JavaScript
/**
* A simple interface to LocalStorage based on [store.js](https://github.com/marcuswestin/store.js), whose sole purpose is to ensure that any keys you save to LocalStorage come out the same type as when they went in.
*
* Normally when you save something to LocalStorage, it converts it into a string. So if you were to save a number, it would be saved as `"12"` instead of `12`. This means when you retrieved the number, it would now be a string.
*
* ```js
* import { setStoreItem, getStoreItem } from 'kontra';
*
* setStoreItem('highScore', 100);
* getStoreItem('highScore'); //=> 100
* ```
* @sectionName Store
*/
/**
* Save an item to localStorage.
* @function setStoreItem
*
* @param {String} key - The name of the key.
* @param {*} value - The value to store.
*/
export function setStoreItem(key, value) {
if (value === undefined) {
localStorage.removeItem(key);
}
else {
localStorage.setItem(key, JSON.stringify(value));
}
}
/**
* Retrieve an item from localStorage and convert it back to its original type.
* @function getStoreItem
*
* @param {String} key - Name of the key of the item to retrieve.
*
* @returns {*} The retrieved item.
*/
export function getStoreItem(key) {
let value = localStorage.getItem(key);
try {
value = JSON.parse(value);
}
catch(e) {}
return value;
}