Skip to content

Instantly share code, notes, and snippets.

@itsmikeq
Created August 30, 2015 01:39
Show Gist options
  • Save itsmikeq/3af18167ed86a2921144 to your computer and use it in GitHub Desktop.
Save itsmikeq/3af18167ed86a2921144 to your computer and use it in GitHub Desktop.
JavaScript local storage
Storage.prototype.setObject = function (_key, _value) {
return this.setItem(_key, JSON.stringify({timestamp: new Date().getTime(), data: _value }));
};
// Clears stuff older than 2 hours
Storage.prototype.clearOld = function () {
_t_date = new Date().getTime();
for (var i = 0; i < Storage.prototype.length; i++) {
if ((_t_date - this.key(i).timestamp) > 7200) {
this.removeItem(this.key(i));
}
}
};
Storage.prototype.getObject = function (_key) {
var r = null;
try {
r = JSON.parse(this.getItem(_key)).data;
} catch (e) {
r = null;
}
if (r && r.data) {
return r.data;
} else {
return r;
}
};
Storage.prototype.appendObject = function (_key, _values) {
// Grab the old
var newValues = this.getObject(_key);
if (newValues === null) {
newValues = [];
}
if (_values instanceof Array) {
for (var i = 0; i < _values.length; i++) {
// Fill with new if not a dupe
if (newValues.indexOf(_values) == -1) {
newValues.push(_values[i]);
}
}
} else {
if (newValues.indexOf(_values) == -1) {
// Append if not a dupe
newValues.push(_values);
}
}
this.setObject(_key, newValues); // Write out
};
Storage.prototype.removeObjects = function (_key, _values) {
for (var i = 0; i < _values.length; i++) {
this.removeObject(_key, _values[i]);
}
};
Storage.prototype.removeObject = function (_key, _value) {
if (_value.iterator !== undefined) {
// Iterable, so return with removeObjects
return this.removeObjects(_key, _value);
}
var oldValues = this.getObject(_key);
if (oldValues != null) {
var removeIndex = oldValues.indexOf(_value);
} else {
// Key does not exist
return true;
}
if (removeIndex === -1) {
// Does not exist
return true;
} else {
oldValues.splice(removeIndex);
this.setObject(_key, oldValues);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment