client/components/yields/store/master/index.js
/**
* dependencies.
*/
var unserialize = require('unserialize');
var each = require('each');
var storage;
/**
* Safari throws when a user
* blocks access to cookies / localstorage.
*/
try {
storage = window.localStorage;
} catch (e) {
storage = null;
}
/**
* Expose `store`
*/
module.exports = store;
/**
* Store the given `key`, `val`.
*
* @param {String|Object} key
* @param {Mixed} value
* @return {Mixed}
* @api public
*/
function store(key, value){
var length = arguments.length;
if (0 == length) return all();
if (2 <= length) return set(key, value);
if (1 != length) return;
if (null == key) return storage.clear();
if ('string' == typeof key) return get(key);
if ('object' == typeof key) return each(key, set);
}
/**
* supported flag.
*/
store.supported = !! storage;
/**
* Set `key` to `val`.
*
* @param {String} key
* @param {Mixed} val
*/
function set(key, val){
return null == val
? storage.removeItem(key)
: storage.setItem(key, JSON.stringify(val));
}
/**
* Get `key`.
*
* @param {String} key
* @return {Mixed}
*/
function get(key){
return unserialize(storage.getItem(key));
}
/**
* Get all.
*
* @return {Object}
*/
function all(){
var len = storage.length;
var ret = {};
var key;
while (0 <= --len) {
key = storage.key(len);
ret[key] = get(key);
}
return ret;
}