record.js/dist/record.min.js

2 lines
1.4 KiB
JavaScript
Raw Normal View History

2018-04-07 04:19:31 +00:00
/*! Record.js | MIT | https://github.com/n2geoff/record.js */
(function(r,t){"use strict";"object"==typeof module&&module.exports?module.exports=t(r.Record):r.Record=t(r.Record)}(this,function(){"use strict";return class{constructor(r){if(this.store=(r||{}).store,this.debug=(r||{}).debug||!1,this.records=[],this.store&&localStorage){this._log("Initializing localStorage for "+this.store);let r=this._load()||[];this.records=[...r]}}_log(){this.debug&&console.log(...arguments)}add(r){if(Array.isArray(r)){let t=[];return r.forEach(()=>{r.id||(r.id=Math.random().toString(36).substr(2,9)),this.records.push(r),this.entries.push(r)}),this._save(),t}return r.id||(r.id=Math.random().toString(36).substr(2,9)),this.records.push(r),this._save(),r}find(r){if(!r)return this.records;if("string"==typeof r||"number"==typeof r)return this.records.filter(t=>t.id===r);let t=Object.keys(r);return this.records.filter(e=>-1!==t.indexOf("id")?e.id===r.id:t.every(t=>e[t]===r[t]))}remove(r){if(!r||Array.isArray(r))return this._log(console.error("remove() accepts a single object")),[];let t=this.find(r);return t.forEach(r=>{this.records.splice(this.records.indexOf(r),1)}),this._save(),t}clear(){this.records=[],this._save()}count(){return this.records.length}_save(){this.store&&localStorage&&localStorage.setItem(this.store,JSON.stringify(this.records))}_load(){if(this.store&&localStorage)return JSON.parse(localStorage.getItem(this.store))||[]}dump(){}}}));