UNPKG

lokijs

Version:

Fast document oriented javascript in-memory database

1 lines 28 kB
!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.loki=e()}(this,function(){return function(){"use strict";function t(t,e){var i,s=e||"parse-stringify";return"parse-stringify"===s&&(i=JSON.parse(JSON.stringify(t))),i}function e(){try{return"localStorage"in window&&null!==window.localStorage}catch(t){return!1}}function i(){}function s(t,e){t.apply(null,e)}function n(t,e){this.filename=t||"loki.db",this.collections=[],this.databaseVersion=1.1,this.engineVersion=1.1,this.autosave=!1,this.autosaveInterval=5e3,this.autosaveHandle=null,this.options={},this.persistenceMethod=null,this.persistenceAdapter=null,"undefined"!=typeof e&&this.configureOptions(e,!0),this.events={init:[],flushChanges:[],close:[],changes:[],warning:[]};var i=function(){return c?"NODEJS":void 0!==document?-1===document.URL.indexOf("http://")&&-1===document.URL.indexOf("https://")?"CORDOVA":"BROWSER":"CORDOVA"};this.ENV=i(),"NODEJS"===this.ENV&&(this.fs=c),this.on("init",this.clearChanges)}function r(t,e,i,s){return this.collection=t,this.searchIsChained=!e&&!i,this.filteredrows=[],this.filterInitialized=!1,"undefined"!=typeof e&&null!==e?this.find(e,s):"undefined"!=typeof i&&null!==i?this.where(i):this}function o(t,e,i){this.collection=t,this.name=e,this.persistent=!1,"undefined"!=typeof i&&(this.persistent=i),this.resultset=new r(t),this.resultdata=[],this.resultsdirty=!1,this.cachedresultset=null,this.filterPipeline=[],this.sortFunction=null,this.sortCriteria=null,this.sortDirty=!1,this.events={rebuild:[]}}function a(t,e){function i(t,e,i){u.changes.push({name:t,operation:e,obj:JSON.parse(JSON.stringify(i))})}function s(){u.changes=[]}function n(t){t&&(t.meta||(t.meta={}),t.meta.created=(new Date).getTime(),t.meta.revision=0)}function r(t){t&&(t.meta.updated=(new Date).getTime(),t.meta.revision+=1)}function o(t){i(u.name,"I",t)}function a(t){i(u.name,"U",t)}function l(t){n(t),o(t)}function h(t){r(t),a(t)}function c(){p=u.disableChangesApi?n:l,y=u.disableChangesApi?r:h}this.name=t,this.data=[],this.idIndex=[],this.binaryIndices={},this.objType=t,this.dirty=!1,this.cachedIndex=null,this.cachedBinaryIndex=null,this.cachedData=null;var u=this;e=e||{},this.transactional=e.hasOwnProperty("transactional")?e.transactional:!1,this.cloneObjects=e.hasOwnProperty("clone")?e.clone:!1,this.asyncListeners=e.hasOwnProperty("asyncListeners")?e.asyncListeners:!0,this.disableChangesApi=e.hasOwnProperty("disableChangesApi")?e.disableChangesApi:!0,this.maxId=0,this.DynamicViews=[],this.events={insert:[],update:[],close:[],flushbuffer:[],error:[],"delete":[],warning:[]},this.changes=[],this.ensureId();var d;d=e?e.indices||[]:[];for(var f=0;f<d.length;f++)this.ensureIndex(d[f]);this.getChanges=function(){return u.changes},this.flushChanges=s;var p,y;c(),this.setChangesApi=function(t){u.disableChangesApi=!t,c()},this.on("insert",function(t){p(t)}),this.on("update",function(t){y(t)}),this.on("delete",function(t){u.disableChangesApi||i(u.name,"R",t)}),this.on("warning",console.warn),s()}var l={copyProperties:function(t,e){var i;for(i in t)e[i]=t[i]}},h={$eq:function(t,e){return t===e},$gt:function(t,e){return t>e},$gte:function(t,e){return t>=e},$lt:function(t,e){return e>t},$lte:function(t,e){return e>=t},$ne:function(t,e){return t!==e},$regex:function(t,e){return e.test(t)},$in:function(t,e){return e.indexOf(t)>-1},$contains:function(t,e){return Array.isArray(t)?-1!==t.indexOf(e):"string"==typeof t?-1!==t.indexOf(e):t&&"object"==typeof t?t.hasOwnProperty(e):void 0}},c="object"==typeof exports?require("fs"):!1;return i.prototype.events={},i.prototype.asyncListeners=!1,i.prototype.on=function(t,e){var i=this.events[t];return i||(i=this.events[t]=[]),i.push(e)-1},i.prototype.emit=function(t){var e=Array.prototype.slice.call(arguments,0),i=this;if(!t||!this.events[t])throw new Error("No event "+t+" defined");e.splice(0,1),this.events[t].forEach(function(t){i.asyncListeners?setTimeout(function(){s(t,e)},1):s(t,e)})},i.prototype.remove=function(t,e){this.events[t]&&this.events[t].splice(e,1)},n.prototype=new i,n.prototype.configureOptions=function(t,e){this.options={},"undefined"!=typeof t&&(this.options=t),this.persistenceMethod=null,this.options.hasOwnProperty("persistenceMethod")&&(this.persistenceMethod=t.persistenceMethod),this.persistenceAdapter=null,this.options.hasOwnProperty("adapter")&&(this.persistenceMethod="adapter",this.persistenceAdapter=t.adapter),t.hasOwnProperty("autoload")&&"undefined"!=typeof e&&e&&this.loadDatabase({},t.autoloadCallback),this.options.hasOwnProperty("autosaveInterval")&&(this.autosaveDisable(),this.autosaveInterval=parseInt(this.options.autosaveInterval)),this.options.hasOwnProperty("autosave")&&this.options.autosave&&(this.autosaveDisable(),this.autosave=!0,this.autosaveEnable())},n.prototype.anonym=function(t,e){var i=new a("anonym",e);return i.insert(t),i},n.prototype.addCollection=function(t,e){var i=new a(t,e);return this.collections.push(i),i},n.prototype.loadCollection=function(t){if(!t.name)throw new Error("Collection must be have a name property to be loaded");this.collections.push(t)},n.prototype.getCollection=function(t){var e,i=this.collections.length;for(e=0;i>e;e+=1)if(this.collections[e].name===t)return this.collections[e];return this.emit("warning","collection "+t+" not found"),null},n.prototype.listCollections=function(){for(var t=this.collections.length,e=[];t--;)e.push({name:this.collections[t].name,type:this.collections[t].objType,count:this.collections[t].data.length});return e},n.prototype.removeCollection=function(t){var e,i=this.collections.length;for(e=0;i>e;e+=1)if(this.collections[e].name===t)return void this.collections.splice(e,1);throw"No such collection"},n.prototype.getName=function(){return this.name},n.prototype.serialize=function(){return JSON.stringify(this)},n.prototype.toJson=n.prototype.serialize,n.prototype.loadJSON=function(t,e){var i,s,n,r,o=JSON.parse(t),a=0,h=o.collections.length,c=!1;for(this.name=o.name,this.databaseVersion=1,o.hasOwnProperty("databaseVersion")&&(this.databaseVersion=o.databaseVersion),this.databaseVersion!==this.engineVersion&&(c=!0),this.collections=[],a;h>a;a+=1){if(i=o.collections[a],s=this.addCollection(i.name),n=i.data.length,r=0,e&&e.hasOwnProperty(i.name)){var u=e[i.name].inflate?e[i.name].inflate:l.copyProperties;for(r;n>r;r++){var o=new e[i.name].proto;u(i.data[r],o),s.data[r]=o}}else for(r;n>r;r++)s.data[r]=i.data[r];if(c&&1.1==this.engineVersion){if(s.transactional=!1,s.cloneObjects=!1,s.asyncListeners=!0,s.disableChangesApi=!0,console.warn("upgrading database, loki id is now called '$loki' instead of 'id'"),s.data.length>0&&!s.data[0].hasOwnProperty("$loki"))for(var d=s.data.length,f=null,p=0;d>p;p++)f=s.data[p],f.$loki=f.id,delete f.id,f.hasOwnProperty.originalId&&(f.id=f.originalId)}else s.transactional=i.transactional,s.asyncListeners=i.asyncListeners,s.disableChangesApi=i.disableChangesApi,s.cloneObjects=i.cloneObjects;if(s.maxId=0===i.data.length?0:i.maxId,s.idIndex=i.idIndex,"undefined"!=typeof i.indices&&(s.idIndex=i.indices.id),"undefined"!=typeof i.binaryIndices&&(s.binaryIndices=i.binaryIndices),s.ensureId(),"undefined"!=typeof i.DynamicViews)for(var p=0;p<i.DynamicViews.length;p++){var y=i.DynamicViews[p],v=s.addDynamicView(y.name,y.persistent);if(v.resultdata=y.resultdata,v.resultsdirty=y.resultsdirty,v.filterPipeline=y.filterPipeline,c&&"undefined"!=typeof y.sortColumn&&null!=y.sortColumn){var g=!1;"undefined"!=typeof y.sortColumnDesc&&(g=y.sortColumnDesc),v.sortCriteria=[y.sortColumn,g]}else v.sortCriteria=y.sortCriteria;v.sortFunction=null,v.sortDirty=y.sortDirty,v.resultset.filteredrows=y.resultset.filteredrows,v.resultset.searchIsChained=y.resultset.searchIsChained,v.resultset.filterInitialized=y.resultset.filterInitialized,v.rematerialize({removeWhereFilters:!0})}}},n.prototype.close=function(t){this.autosave&&(this.autosaveDisable(),this.autosaveDirty()&&this.saveDatabase()),t&&this.on("close",t),this.emit("close")},n.prototype.generateChangesNotification=function(t){function e(t){return t.name}var i=[],s=t||this.collections.map(e);return this.collections.forEach(function(t){-1!==s.indexOf(e(t))&&(i=i.concat(t.getChanges()))}),i},n.prototype.serializeChanges=function(t){return JSON.stringify(this.generateChangesNotification(t))},n.prototype.clearChanges=function(){this.collections.forEach(function(t){t.flushChanges&&t.flushChanges()})},n.prototype.loadDatabase=function(t,i){var s=i||function(t){if(t)throw t},n=this;return null!=this.persistenceMethod?("fs"===this.persistenceMethod&&this.fs.readFile(this.filename,{encoding:"utf8"},function(e,i){return e?s(e,null):(n.loadJSON(i,t||{}),void s(null,i))}),"localStorage"===this.persistenceMethod&&(e()?(n.loadJSON(localStorage.getItem(this.filename)),s(null,data)):s(new Error("localStorage is not available"))),void("adapter"===this.persistenceMethod&&(null!==this.persistenceAdapter?this.persistenceAdapter.loadDatabase(this.filename,function(t){"undefined"==typeof t||null===t?(console.warn("lokijs loadDatabase : Database not found"),s("Database not found")):(n.loadJSON(t),s(null))}):s(new Error("persistenceAdapter not configured"))))):void("NODEJS"===this.ENV?this.fs.readFile(this.filename,{encoding:"utf8"},function(e,i){return e?s(e,null):(n.loadJSON(i,t||{}),void s(null,i))}):"BROWSER"===this.ENV?e()?(n.loadJSON(localStorage.getItem(this.filename)),s(null,data)):s(new Error("localStorage is not available")):s(new Error("unknown environment")))},n.prototype.saveDatabase=function(t){var i=t||function(t){if(t)throw t},s=this;return this.autosaveClearFlags(),null!=this.persistenceMethod?("fs"===this.persistenceMethod&&s.fs.writeFile(s.filename,s.serialize(),i),"localStorage"===this.persistenceMethod&&(e()?(localStorage.setItem(s.filename,s.serialize()),i(null)):i(new Error("localStorage is not available"))),void("adapter"===this.persistenceMethod&&(null!==this.persistenceAdapter?this.persistenceAdapter.saveDatabase(this.filename,s.serialize(),function(){i(null)}):i(new Error("persistenceAdapter not configured"))))):void("NODEJS"===this.ENV?s.fs.writeFile(s.filename,s.serialize(),i):"BROWSER"===this.ENV||"CORDOVA"===this.ENV?e()?(localStorage.setItem(s.filename,s.serialize()),i(null)):i(new Error("localStorage is not available")):i(new Error("unknown environment")))},n.prototype.save=n.prototype.saveDatabase,n.prototype.autosaveDirty=function(){for(var t=0;t<this.collections.length;t++)if(this.collections[t].dirty)return!0;return!1},n.prototype.autosaveClearFlags=function(){for(var t=0;t<this.collections.length;t++)this.collections[t].dirty=!1},n.prototype.autosaveEnable=function(){this.autosave=!0;var t=5e3,e=this;"undefined"!=typeof this.autosaveInterval&&null!==this.autosaveInterval&&(t=this.autosaveInterval),this.autosaveHandle=setInterval(function(){e.autosaveDirty()&&e.saveDatabase()},t)},n.prototype.autosaveDisable=function(){"undefined"!=typeof this.autosaveHandle&&null!==this.autosaveHandle&&(clearInterval(this.autosaveHandle),this.autosaveHandle=null)},r.prototype.toJSON=function(){var t=this.copy();return t.collection=null,t},r.prototype.limit=function(t){this.searchIsChained&&!this.filterInitialized&&0===this.filteredrows.length&&(this.filteredrows=Object.keys(this.collection.data));var e=this.copy();return e.filteredrows=e.filteredrows.slice(0,t),e},r.prototype.offset=function(t){this.searchIsChained&&!this.filterInitialized&&0===this.filteredrows.length&&(this.filteredrows=Object.keys(this.collection.data));var e=this.copy();return e.filteredrows=e.filteredrows.splice(t,e.filteredrows.length),e},r.prototype.copy=function(){var t=new r(this.collection,null,null);return t.filteredrows=this.filteredrows.slice(),t.filterInitialized=this.filterInitialized,t},r.prototype.branch=r.prototype.copy,r.prototype.sort=function(t){this.searchIsChained&&!this.filterInitialized&&0===this.filteredrows.length&&(this.filteredrows=Object.keys(this.collection.data));var e=function(t,e){return function(i,s){var n=e.collection.data[i],r=e.collection.data[s];return t(n,r)}}(t,this);return this.filteredrows.sort(e),this},r.prototype.simplesort=function(t,e){this.searchIsChained&&!this.filterInitialized&&0===this.filteredrows.length&&(this.filteredrows=Object.keys(this.collection.data)),"undefined"==typeof e&&(e=!1);var i=function(t,e,i){return function(s,n){var r=i.collection.data[s],o=i.collection.data[n];if(r[t]===o[t])return 0;if(e){if(r[t]<o[t])return 1;if(r[t]>o[t])return-1}else{if(r[t]>o[t])return 1;if(r[t]<o[t])return-1}}}(t,e,this);return this.filteredrows.sort(i),this},r.prototype.compoundeval=function(t,e,i){var s=t.length;if(0===s)throw new Error("Invalid call to compoundeval, need at least one property");var n=!1,r=t[0];return"string"!=typeof r&&Array.isArray(r)&&(n=r[1],r=r[0]),e[r]===i[r]?1===s?0:this.compoundeval(t.slice(1),e,i,n):n?e[r]<i[r]?1:-1:e[r]>i[r]?1:-1},r.prototype.compoundsort=function(t){this.searchIsChained&&!this.filterInitialized&&0===this.filteredrows.length&&(this.filteredrows=Object.keys(this.collection.data));var e=function(t,e){return function(i,s){var n=e.collection.data[i],r=e.collection.data[s];return e.compoundeval(t,n,r)}}(t,this);return this.filteredrows.sort(e),this},r.prototype.calculateRange=function(t,e,i){var s=this.collection.data,n=this.collection.binaryIndices[e].values,r=0,o=n.length-1,a=null,l=0,h=n.length-1;if(0==s.length)return[0,-1];var c=s[n[r]][e],u=s[n[o]][e];switch(t){case"$eq":if(c>i||i>u)return[0,-1];break;case"$gt":if(i>=u)return[0,-1];break;case"$gte":if(i>u)return[0,-1];break;case"$lt":if(c>=i)return[0,-1];break;case"$lte":if(c>i)return[0,-1]}for(;o>r;)a=Math.floor((r+o)/2),s[n[a]][e]<i?r=a+1:o=a;for(l=r,r=0,o=n.length-1;o>r;)a=Math.floor((r+o)/2),i<s[n[a]][e]?o=a:r=a+1;h=o;var d=s[n[l]][e],f=s[n[h]][e];switch(t){case"$eq":return d!==i?[0,-1]:(f!==i&&h--,[l,h]);case"$gt":return i>=f?[0,-1]:[h,s.length-1];case"$gte":return i>d?[0,-1]:[l,s.length-1];case"$lt":return[0,l-1];case"$lte":return f!==i&&h--,[0,h];default:return[0,s.length-1]}},r.prototype.find=function(t,e){if(0===this.collection.data.length)return this.searchIsChained?(this.filteredrows=[],this.filterInitialized=!0,this):[];var i,s,n,r,o,a,l,c,u,d=t||"getAll",f={$eq:h.$eq,$gt:h.$gt,$gte:h.$gte,$lt:h.$lt,$lte:h.$lte,$ne:h.$ne,$regex:h.$regex,$in:h.$in,$contains:h.$contains},p=!1,y=[],v=null;if("undefined"==typeof e&&(e=!1),"getAll"===d)return this.searchIsChained?(this.filteredrows=Object.keys(this.collection.data),this):this.collection.data;var g=!1;for(r in d)if(d.hasOwnProperty(r)){if(i=r,-1!=r.indexOf(".")&&(g=!0),"object"!=typeof d[r])n="$eq",s=d[r];else{if("object"!=typeof d[r])throw"Do not know what you want to do.";for(o in d[r])d[r].hasOwnProperty(o)&&(n=o,s=d[r][o])}break}if("$regex"===n&&(s=RegExp(s)),null===this.collection.data)throw new TypeError;if((!this.searchIsChained||this.searchIsChained&&!this.filterInitialized)&&"$ne"!==n&&"$regex"!==n&&"$contains"!==n&&"$in"!==n&&this.collection.binaryIndices.hasOwnProperty(i)&&(this.collection.ensureIndex(i),p=!0,v=this.collection.binaryIndices[i]),a=f[n],this.searchIsChained){if(this.filterInitialized){if(p)for(l=v,c=this.filteredrows.length;c--;)a(l[this.filteredrows[c]],s)&&y.push(this.filteredrows[c]);else if(l=this.collection.data,c=this.filteredrows.length,g)for(var w,m;c--;)w=l[this.filteredrows[c]],m=i.split("."),m.forEach(function(t){w=w[t]}),a(w,s)&&y.push(this.filteredrows[c]);else for(;c--;)a(l[this.filteredrows[c]][i],s)&&y.push(this.filteredrows[c]);return this.filteredrows=y,this}if(p){l=this.collection.data;for(var I=this.calculateRange(n,i,s,this),b=I[0];b<=I[1];b++)y.push(v.values[b]);this.filteredrows=y}else if(l=this.collection.data,c=l.length,g)for(var w,m;c--;)w=l[c],m=i.split("."),m.forEach(function(t){w=w[t]}),a(w,s)&&y.push(c);else for(;c--;)a(l[c][i],s)&&y.push(c);return this.filteredrows=y,this.filterInitialized=!0,this}if(p){l=this.collection.data,u=l.length;var I=this.calculateRange(n,i,s,this);if(e)return-1!==I[1]?this.data[I[0]]:[];for(c=I[0];c<=I[1];c++)y.push(l[v.values[c]]);this.filteredrows=y}else{if(l=this.collection.data,c=l.length,e){for(;c--;)if(a(l[c][i],s))return l[c];return[]}if(g)for(var w,m;c--;)w=l[c],m=i.split("."),m.forEach(function(t){w=w[t]}),a(w,s)&&y.push(l[c]);else for(;c--;)a(l[c][i],s)&&y.push(l[c])}return y},r.prototype.where=function(t){var e,i=[];if("function"!=typeof t)throw"Argument is not a stored view or a function";e=t;try{if(this.searchIsChained){if(this.filterInitialized){for(var s=this.filteredrows.length;s--;)e(this.collection.data[this.filteredrows[s]])===!0&&i.push(this.filteredrows[s]);return this.filteredrows=i,this}for(var s=this.collection.data.length;s--;)e(this.collection.data[s])===!0&&i.push(s);return this.filteredrows=i,this.filterInitialized=!0,this}for(var s=this.collection.data.length;s--;)e(this.collection.data[s])===!0&&i.push(this.collection.data[s]);return i}catch(n){throw n}},r.prototype.data=function(){var t=[];if(this.searchIsChained&&!this.filterInitialized){if(0===this.filteredrows.length)return this.collection.data;this.filterInitialized=!0}var e,i=this.collection.data,s=this.filteredrows,n=this.filteredrows.length;for(e=0;n>e;e++)t.push(i[s[e]]);return t},r.prototype.update=function(t){if("function"!=typeof t)throw"Argument is not a function";this.searchIsChained&&!this.filterInitialized&&0===this.filteredrows.length&&(this.filteredrows=Object.keys(this.collection.data));for(var e=this.filteredrows.length,i=this.collection.data,s=0;e>s;s++)t(i[this.filteredrows[s]]),this.collection.update(i[this.filteredrows[s]]);return this},r.prototype.remove=function(){this.searchIsChained&&!this.filterInitialized&&0===this.filteredrows.length&&(this.filteredrows=Object.keys(this.collection.data));for(var t=this.filteredrows.length,e=0;t>e;e++)this.collection.remove(this.filteredrows[e]);return this.filteredrows=[],this},r.prototype.mapReduce=function(t,e){try{return e(this.data().map(t))}catch(i){throw i}},o.prototype=new i,o.prototype.rematerialize=function(t){var e,i,s;if(t=t||{},this.resultdata=[],this.resultsdirty=!0,this.resultset=new r(this.collection),(this.sortFunction||this.sortCriteria)&&(this.sortDirty=!0),t.hasOwnProperty("removeWhereFilters"))for(e=this.filterPipeline.length,i=e;i--;)"where"===this.filterPipeline[i].type&&(i!==this.filterPipeline.length-1&&(this.filterPipeline[i]=this.filterPipeline[this.filterPipeline.length-1]),this.filterPipeline.length--);var n=this.filterPipeline;for(this.filterPipeline=[],e=n.length,s=0;e>s;s++)this.applyFind(n[s].val);return this.data(),this.emit("rebuild",this),this},o.prototype.branchResultset=function(){return this.resultset.copy()},o.prototype.toJSON=function(){var t=new o(this.collection,this.name,this.persistent);return t.resultset=this.resultset,t.resultdata=[],t.resultsdirty=!0,t.filterPipeline=this.filterPipeline,t.sortFunction=this.sortFunction,t.sortCriteria=this.sortCriteria,t.sortDirty=this.sortDirty,t.collection=null,t},o.prototype.applySort=function(t){return this.sortFunction=t,this.sortCriteria=null,this.resultset.sort(t),this.sortDirty=!1,this},o.prototype.applySimpleSort=function(t,e){return"undefined"==typeof e&&(e=!1),this.sortCriteria=[[t,e]],this.sortFunction=null,this.resultset.simplesort(t,e),this.sortDirty=!1,this},o.prototype.applySortCriteria=function(t){return this.sortCriterial=t,this.sortFunction=null,this.resultset.compoundsort(t),this.sortDirty=!1,this},o.prototype.startTransaction=function(){return this.cachedresultset=this.resultset.copy(),this},o.prototype.commit=function(){return this.cachedresultset=null,this},o.prototype.rollback=function(){return this.resultset=this.cachedresultset,this.persistent&&(this.resultdata=this.resultset.data(),this.emit("rebuild",this)),this},o.prototype.applyFind=function(t){return this.filterPipeline.push({type:"find",val:t}),this.resultset.find(t),(this.sortFunction||this.sortCriteria)&&(this.sortDirty=!0),this.persistent&&(this.resultsdirty=!0),this},o.prototype.applyWhere=function(t){return this.filterPipeline.push({type:"where",val:t}),this.resultset.where(t),(this.sortFunction||this.sortCriteria)&&(this.sortDirty=!0),this.persistent&&(this.resultsdirty=!0),this},o.prototype.data=function(){return this.sortDirty&&(this.sortFunction&&this.resultset.sort(this.sortFunction),this.sortCriteria&&this.resultset.compoundsort(this.sortCriteria),this.sortDirty=!1,this.persistent&&(this.resultsdirty=!0)),this.persistent?(this.resultsdirty&&(this.resultdata=this.resultset.data(),this.resultsdirty=!1,this.emit("rebuild",this)),this.resultdata):(this.resultset.filterInitialized||this.emit("rebuild",this),this.resultset.data())},o.prototype.evaluateDocument=function(t){var e=this.resultset.filteredrows,i=e.indexOf(t),s=e.length,n=new r(this.collection);n.filteredrows=[t],n.filterInitialized=!0;for(var o=0;o<this.filterPipeline.length;o++)switch(this.filterPipeline[o].type){case"find":n.find(this.filterPipeline[o].val);break;case"where":n.where(this.filterPipeline[o].val)}var a=0===n.filteredrows.length?-1:0;return-1!=i||-1!=a?-1===i&&-1!==a?(e.push(t),this.persistent&&this.resultdata.push(this.collection.data[t]),void((this.sortFunction||this.sortCriteria)&&(this.sortDirty=!0))):-1!==i&&-1===a?void(s-1>i?(e[i]=e[s-1],e.length=s-1,this.persistent&&(this.resultdata[i]=this.resultdata[s-1],this.resultdata.length=s-1)):(e.length=s-1,this.persistent&&(this.resultdata.length=s-1))):-1!==i&&-1!==a?(this.persistent&&(this.resultdata[i]=this.collection.data[t]),void((this.sortFunction||this.sortCriteria)&&(this.sortDirty=!0))):void 0:void 0},o.prototype.removeDocument=function(t){var e=this.resultset.filteredrows,i=e.indexOf(t),s=e.length;-1!==i&&(s-1>i?(e[i]=e[s-1],e.length=s-1,this.resultdata[i]=this.resultdata[s-1],this.resultdata.length=s-1):(e.length=s-1,this.resultdata.length=s-1))},o.prototype.mapReduce=function(t,e){try{return e(this.data().map(t))}catch(i){throw i}},a.prototype=new i,a.prototype.ensureIndex=function(t,e){if("undefined"==typeof e&&(e=!1),null===t||void 0===t)throw"Attempting to set index without an associated property";if(!this.binaryIndices.hasOwnProperty(t)||e||this.binaryIndices[t].dirty){this.binaryIndices[t]={name:t,dirty:!0,values:[]};var i,s=this.data.length,n=0;for(i=this.binaryIndices[t],n;s>n;n+=1)i.values.push(n);var r=function(t,e){return function(i,s){var n=e.data[i],r=e.data[s];return n[t]===r[t]?0:n[t]>r[t]?1:n[t]<r[t]?-1:void 0}}(t,this);i.values.sort(r),i.dirty=!1,this.dirty=!0}},a.prototype.ensureAllIndexes=function(t){for(var e=Object.keys(this.binaryIndices),i=e.length;i--;)this.ensureIndex(e[i],t)},a.prototype.flagBinaryIndexesDirty=function(){for(var t=Object.keys(this.binaryIndices),e=t.length;e--;)this.binaryIndices[t[e]].dirty=!0},a.prototype.ensureId=function(){var t=this.data.length,e=0;for(this.idIndex=[],e;t>e;e+=1)this.idIndex.push(this.data[e].$loki)},a.prototype.ensureIdAsync=function(t){this.async(function(){this.ensureId()},t)},a.prototype.addDynamicView=function(t,e){var i=new o(this,t,e);return this.DynamicViews.push(i),i},a.prototype.removeDynamicView=function(t){for(var e=0;e<this.DynamicViews.length;e++)this.DynamicViews[e].name===t&&this.DynamicViews.splice(e,1)},a.prototype.getDynamicView=function(t){for(var e=0;e<this.DynamicViews.length;e++)if(this.DynamicViews[e].name===t)return this.DynamicViews[e];return null},a.prototype.findAndUpdate=function(t,e){var i,s=this.where(t),n=0;try{for(n;n<s.length;n++)i=e(s[n]),this.update(i)}catch(r){this.rollback(),console.error(r.message)}},a.prototype.insert=function(t){var e,i=this;if(Array.isArray(t))return t.forEach(function(t){e=i.clone?JSON.parse(JSON.stringify(t)):t,"undefined"==typeof e.meta&&(e.meta={revision:0,created:0}),i.add(e),i.emit("insert",e)}),e;if("object"!=typeof t)throw new TypeError("Document needs to be an object");if(!t){var s=new Error("Object cannot be null");throw this.emit("error",s),s}return e=i.clone?JSON.parse(JSON.stringify(t)):t,"undefined"==typeof t.meta&&(e.meta={revision:0,created:0}),i.add(e),i.emit("insert",e),e},a.prototype.clear=function(){this.data=[],this.idIndex=[],this.binaryIndices={},this.cachedIndex=null,this.cachedData=null,this.maxId=0,this.DynamicViews=[],this.dirty=!0},a.prototype.update=function(t){if(Object.keys(this.binaryIndices).length>0&&this.flagBinaryIndexesDirty(),Array.isArray(t)){var e=0,i=t.length;for(e;i>e;e+=1)this.update(t[e])}else{if(!t.hasOwnProperty("$loki"))throw"Trying to update unsynced document. Please save the document first by using insert() or addMany()";try{this.startTransaction();var s,n,r=this.get(t.$loki,!0);if(!r)throw new Error("Trying to update a document not in collection.");s=r[0],n=r[1],this.data[n]=t;for(var o=0;o<this.DynamicViews.length;o++)this.DynamicViews[o].evaluateDocument(n);this.idIndex[n]=s.$loki,this.commit(),this.dirty=!0,this.emit("update",t)}catch(a){throw this.rollback(),console.error(a.message),this.emit("error",a),a}}},a.prototype.add=function(t){var e,i=this.DynamicViews.length;if("object"!=typeof t)throw"Object being added needs to be an object";if(Object.keys(this.binaryIndices).length>0&&this.flagBinaryIndexesDirty(),"undefined"!=typeof t.$loki)throw"Document is already in collection, please use update()";try{this.startTransaction(),this.maxId++;var e;for(isNaN(this.maxId)&&(this.maxId=this.data[this.data.length-1].$loki+1),t.$loki=this.maxId,t.meta.version=0,this.data.push(t),e=0;i>e;e++)this.DynamicViews[e].evaluateDocument(this.data.length-1);return this.idIndex.push(t.$loki),this.commit(),this.dirty=!0,t}catch(s){this.rollback(),console.error(s.message)}},a.prototype.remove=function(t){if("object"!=typeof t)throw new Error("Parameter is not an object");if(Array.isArray(t)){var e=0,i=t.length;for(e;i>e;e+=1)this.remove(t[e])}else{if(!t.hasOwnProperty("$loki"))throw new Error("Object is not a document stored in the collection");Object.keys(this.binaryIndices).length>0&&this.flagBinaryIndexesDirty();try{this.startTransaction();for(var s=this.get(t.$loki,!0),n=s[1],r=0;r<this.DynamicViews.length;r++)this.DynamicViews[r].removeDocument(n);this.data.splice(n,1),this.idIndex.splice(n,1),this.commit(),this.dirty=!0,this.emit("delete")}catch(o){this.rollback(),console.error(o.message),this.emit("error",o)}}},a.prototype.get=function(t,e){var i=e||!1,s=this.idIndex,n=s.length-1,r=0,o=Math.floor(r+(n-r)/2);if(isNaN(t)&&(t=parseInt(t),isNaN(t)))throw"Passed id is not an integer";for(;s[r]<s[n];)o=Math.floor((r+n)/2),s[o]<t?r=o+1:n=o;return n===r&&s[r]===t?i?[this.data[r],r]:this.data[r]:null},a.prototype.findOne=function(t){var e=new r(this,t,null,!0);return Array.isArray(e)&&0===e.length?null:e},a.prototype.chain=function(){return new r(this,null,null)},a.prototype.find=function(t){return"undefined"==typeof t&&(t="getAll"),new r(this,t,null)},a.prototype.findOneUnindexed=function(t,e){for(var i,s=this.data.length;s--;)if(this.data[s][t]===e)return i=this.data[s];return null},a.prototype.startTransaction=function(){if(this.transactional){this.cachedData=t(this.data,"parse-stringify"),this.cachedIndex=this.idIndex,this.cachedBinaryIndex=this.binaryIndices;for(var e=0;e<this.DynamicViews.length;e++)this.DynamicViews[e].startTransaction()}},a.prototype.commit=function(){if(this.transactional){this.cachedData=null,this.cachedIndex=null,this.cachedBinaryIndices=null;for(var t=0;t<this.DynamicViews.length;t++)this.DynamicViews[t].commit()}},a.prototype.rollback=function(){if(this.transactional){null!==this.cachedData&&null!==this.cachedIndex&&(this.data=this.cachedData,this.idIndex=this.cachedIndex,this.binaryIndices=this.cachedBinaryIndex);for(var t=0;t<this.DynamicViews.length;t++)this.DynamicViews[t].rollback()}},a.prototype.async=function(t,e){setTimeout(function(){if("function"!=typeof t)throw"Argument passed for async execution is not a function";t(),e()},0)},a.prototype.where=function(t){return new r(this,null,t)},a.prototype.mapReduce=function(t,e){try{return e(this.data.map(t))}catch(i){throw i}},a.prototype.no_op=function(){},n.Collection=a,n}()});