Skip to content

Instantly share code, notes, and snippets.

@Pepijn98
Last active September 12, 2018 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pepijn98/297c1ac992f867c72870a0d24b0ec8f3 to your computer and use it in GitHub Desktop.
Save Pepijn98/297c1ac992f867c72870a0d24b0ec8f3 to your computer and use it in GitHub Desktop.
Extend String and Storage with some useful properties and methods in my opinion
/**
* Set multiple storage items
* @param {Object} items
*/
Storage.prototype.setItems = function (items) {
for (let item in items) {
if (items.hasOwnProperty(item)) {
let itemToSet = "";
if (typeof items[item] === 'object')
itemToSet = JSON.stringify(items[item]);
else
itemToSet = items[item];
this.setItem(item, itemToSet)
}
}
};
/**
* Get multiple storage items
* @returns {Object}
*/
Storage.prototype.getItems = function () {
let obj = {};
for (let item in this) {
if (this.hasOwnProperty(item)) {
let jsonItem = this.getItemAsJson(item);
obj[item] = jsonItem.length > 0 ? jsonItem : Object.keys(jsonItem).length > 0 ? jsonItem : this[item];
}
}
return obj;
};
/**
* Remove multiple storage items
* @param {Array<String>} items
*/
Storage.prototype.removeItems = function (items) {
for (let index = 0; index < items.length; index++)
this.removeItem(items[index]);
};
/**
* Get item as parsed json
* @param {String} key
* @returns {Object|Array}
*/
Storage.prototype.getItemAsJson = function (key) {
return this[key] ? this[key].isJSON ? JSON.parse(this[key]) : [] : [];
};
Object.defineProperties(String.prototype, {
isBlank: {
/**
* Check if string is blank
* @return {Boolean}
*/
get: function () {
return /^\s*$/.test(this);
}
},
isJSON: {
/**
* Check if string is valid json
* @return {Boolean}
*/
get: function () {
let str = this;
if (str.isBlank) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment