Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

lokijs

Package Overview
Dependencies
Maintainers
1
Versions
92
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lokijs - npm Package Compare versions

Comparing version 1.1.15 to 1.2.0

coverage/coverage.json

3

build/lokijs.min.js

@@ -1,2 +0,1 @@

(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.loki=factory()}})(this,function(){return function(){"use strict";var Utils={copyProperties:function(src,dest){var prop;for(prop in src){dest[prop]=src[prop]}}};var LokiOps={$eq:function(a,b){return a===b},$gt:function(a,b){return a>b},$gte:function(a,b){return a>=b},$lt:function(a,b){return a<b},$lte:function(a,b){return a<=b},$ne:function(a,b){return a!==b},$regex:function(a,b){return b.test(a)},$in:function(a,b){return b.indexOf(a)>-1},$contains:function(a,b){var checkFn=function(){return true};if(!Array.isArray(b)){b=[b]}if(Array.isArray(a)){checkFn=function(curr){return a.indexOf(curr)!==-1}}if(typeof a==="string"){checkFn=function(curr){return a.indexOf(curr)!==-1}}if(a&&typeof a==="object"){checkFn=function(curr){return a.hasOwnProperty(curr)}}return b.reduce(function(prev,curr){if(!prev){return prev}return checkFn(curr)},true)}};var fs=typeof exports==="object"?require("fs"):false;function clone(data,method){var cloneMethod=method||"parse-stringify",cloned;if(cloneMethod==="parse-stringify"){cloned=JSON.parse(JSON.stringify(data))}return cloned}function localStorageAvailable(){try{return"localStorage"in window&&window["localStorage"]!==null}catch(e){return false}}function ltHelper(prop1,prop2,equal){if(prop1===prop2){if(equal){return true}else{return false}}if(prop1===undefined){return true}if(prop2===undefined){return false}if(prop1===null){return true}if(prop2===null){return false}return prop1<prop2}function gtHelper(prop1,prop2,equal){if(prop1===prop2){if(equal){return true}else{return false}}if(prop1===undefined){return false}if(prop2===undefined){return true}if(prop1===null){return false}if(prop2===null){return true}return prop1>prop2}function sortHelper(prop1,prop2,desc){if(prop1===prop2){return 0}if(desc){if(ltHelper(prop1,prop2)){return 1}else{return-1}}else{if(gtHelper(prop1,prop2)){return 1}else{return-1}}}function LokiEventEmitter(){}LokiEventEmitter.prototype.events={};LokiEventEmitter.prototype.asyncListeners=false;LokiEventEmitter.prototype.on=function(eventName,listener){var event=this.events[eventName];if(!event){event=this.events[eventName]=[]}return event.push(listener)-1};function applyListener(listener,args){listener.apply(null,args)}LokiEventEmitter.prototype.emit=function(eventName){var args=Array.prototype.slice.call(arguments,0),self=this;if(eventName&&this.events[eventName]){args.splice(0,1);this.events[eventName].forEach(function(listener){if(self.asyncListeners){setTimeout(function(){applyListener(listener,args)},1)}else{applyListener(listener,args)}})}else{throw new Error("No event "+eventName+" defined")}};LokiEventEmitter.prototype.removeListener=function(eventName,index){if(this.events[eventName]){this.events[eventName].splice(index,1)}};function Loki(filename,options){this.filename=filename||"loki.db";this.collections=[];this.databaseVersion=1.1;this.engineVersion=1.1;this.autosave=false;this.autosaveInterval=5e3;this.autosaveHandle=null;this.options={};this.persistenceMethod=null;this.persistenceAdapter=null;this.events={init:[],flushChanges:[],close:[],changes:[],warning:[]};var self=this;var getENV=function(){if(typeof window==="undefined"){return"NODEJS"}if(typeof global!=="undefined"&&global.window){return"NODEJS"}if(typeof document!=="undefined"){if(document.URL.indexOf("http://")===-1&&document.URL.indexOf("https://")===-1){return"CORDOVA"}return"BROWSER"}return"CORDOVA"};if(options&&options.hasOwnProperty("env")){this.ENV=options.env}else{this.ENV=getENV()}if(this.ENV==="undefined"){this.ENV="NODEJS"}if(this.ENV==="NODEJS"){this.fs=fs}if(typeof options!=="undefined"){this.configureOptions(options,true)}this.on("init",this.clearChanges)}Loki.prototype=new LokiEventEmitter;Loki.prototype.configureOptions=function(options,initialConfig){this.options={};if(typeof options!=="undefined"){this.options=options}this.persistenceMethod=null;if(this.options.hasOwnProperty("persistenceMethod")){this.persistenceMethod=options.persistenceMethod}this.persistenceAdapter=null;if(this.options.hasOwnProperty("adapter")){this.persistenceMethod="adapter";this.persistenceAdapter=options.adapter}if(options.hasOwnProperty("autoload")&&typeof initialConfig!=="undefined"&&initialConfig){this.loadDatabase({},options.autoloadCallback)}if(this.options.hasOwnProperty("autosaveInterval")){this.autosaveDisable();this.autosaveInterval=parseInt(this.options.autosaveInterval)}if(this.options.hasOwnProperty("autosave")&&this.options.autosave){this.autosaveDisable();this.autosave=true;this.autosaveEnable()}};Loki.prototype.anonym=function(docs,indexesArray){var collection=new Collection("anonym",indexesArray);collection.insert(docs);return collection};Loki.prototype.addCollection=function(name,options){var collection=new Collection(name,options);this.collections.push(collection);return collection};Loki.prototype.loadCollection=function(collection){if(!collection.name){throw new Error("Collection must be have a name property to be loaded")}this.collections.push(collection)};Loki.prototype.getCollection=function(collectionName){var i,len=this.collections.length;for(i=0;i<len;i+=1){if(this.collections[i].name===collectionName){return this.collections[i]}}this.emit("warning","collection "+collectionName+" not found");return null};Loki.prototype.listCollections=function(){var i=this.collections.length,colls=[];while(i--){colls.push({name:this.collections[i].name,type:this.collections[i].objType,count:this.collections[i].data.length})}return colls};Loki.prototype.removeCollection=function(collectionName){var i,len=this.collections.length;for(i=0;i<len;i+=1){if(this.collections[i].name===collectionName){this.collections.splice(i,1);return}}throw"No such collection"};Loki.prototype.getName=function(){return this.name};Loki.prototype.serializeReplacer=function(key,value){switch(key){case"autosaveHandle":return null;default:return value}};Loki.prototype.serialize=function(){return JSON.stringify(this,this.serializeReplacer)};Loki.prototype.toJson=Loki.prototype.serialize;Loki.prototype.loadJSON=function(serializedDb,options){var obj=JSON.parse(serializedDb),i=0,len=obj.collections.length,coll,copyColl,clen,j,upgradeNeeded=false;this.name=obj.name;this.databaseVersion=1;if(obj.hasOwnProperty("databaseVersion")){this.databaseVersion=obj.databaseVersion}if(this.databaseVersion!==this.engineVersion){upgradeNeeded=true}this.collections=[];for(i;i<len;i+=1){coll=obj.collections[i];copyColl=this.addCollection(coll.name);clen=coll.data.length;j=0;if(options&&options.hasOwnProperty(coll.name)){var loader=options[coll.name]["inflate"]?options[coll.name]["inflate"]:Utils.copyProperties;for(j;j<clen;j++){var obj=new options[coll.name]["proto"];loader(coll.data[j],obj);copyColl.data[j]=obj}}else{for(j;j<clen;j++){copyColl.data[j]=coll.data[j]}}if(upgradeNeeded&&this.engineVersion==1.1){copyColl.transactional=false;copyColl.cloneObjects=false;copyColl.asyncListeners=true;copyColl.disableChangesApi=true;console.warn("upgrading database, loki id is now called '$loki' instead of 'id'");if(copyColl.data.length>0){if(!copyColl.data[0].hasOwnProperty("$loki")){var dlen=copyColl.data.length;var currDoc=null;for(var idx=0;idx<dlen;idx++){currDoc=copyColl.data[idx];currDoc["$loki"]=currDoc["id"];delete currDoc.id;if(currDoc.hasOwnProperty["originalId"]){currDoc["id"]=currDoc["originalId"]}}}}}else{copyColl.transactional=coll.transactional;copyColl.asyncListeners=coll.asyncListeners;copyColl.disableChangesApi=coll.disableChangesApi;copyColl.cloneObjects=coll.cloneObjects}copyColl.maxId=coll.data.length===0?0:coll.maxId;copyColl.idIndex=coll.idIndex;if(typeof coll.indices!=="undefined"){copyColl.idIndex=coll.indices.id}if(typeof coll.binaryIndices!=="undefined"){copyColl.binaryIndices=coll.binaryIndices}copyColl.ensureId();if(typeof coll.DynamicViews==="undefined")continue;for(var idx=0;idx<coll.DynamicViews.length;idx++){var colldv=coll.DynamicViews[idx];var dv=copyColl.addDynamicView(colldv.name,colldv.persistent);dv.resultdata=colldv.resultdata;dv.resultsdirty=colldv.resultsdirty;dv.filterPipeline=colldv.filterPipeline;if(upgradeNeeded&&typeof colldv.sortColumn!=="undefined"&&colldv.sortColumn!=null){var isdesc=false;if(typeof colldv.sortColumnDesc!=="undefined"){isdesc=colldv.sortColumnDesc}dv.sortCriteria=[colldv.sortColumn,isdesc]}else{dv.sortCriteria=colldv.sortCriteria}dv.sortFunction=null;dv.sortDirty=colldv.sortDirty;dv.resultset.filteredrows=colldv.resultset.filteredrows;dv.resultset.searchIsChained=colldv.resultset.searchIsChained;dv.resultset.filterInitialized=colldv.resultset.filterInitialized;dv.rematerialize({removeWhereFilters:true})}}};Loki.prototype.close=function(callback){if(this.autosave){this.autosaveDisable();if(this.autosaveDirty()){this.saveDatabase()}}if(callback){this.on("close",callback)}this.emit("close")};Loki.prototype.generateChangesNotification=function(arrayOfCollectionNames){function getCollName(coll){return coll.name}var changes=[],selectedCollections=arrayOfCollectionNames||this.collections.map(getCollName);this.collections.forEach(function(coll){if(selectedCollections.indexOf(getCollName(coll))!==-1){changes=changes.concat(coll.getChanges())}});return changes};Loki.prototype.serializeChanges=function(collectionNamesArray){return JSON.stringify(this.generateChangesNotification(collectionNamesArray))};Loki.prototype.clearChanges=function(){this.collections.forEach(function(coll){if(coll.flushChanges){coll.flushChanges()}})};Loki.prototype.loadDatabase=function(options,callback){var cFun=callback||function(err,data){if(err){throw err}return},self=this;if(this.persistenceMethod!=null){if(this.persistenceMethod==="fs"){this.fs.readFile(this.filename,{encoding:"utf8"},function readFileCallback(err,data){if(err){return cFun(err,null)}self.loadJSON(data,options||{});cFun(null,data)})}if(this.persistenceMethod==="localStorage"){if(localStorageAvailable()){var data=localStorage.getItem(this.filename);self.loadJSON(data,options||{});cFun(null,data)}else{cFun(new Error("localStorage is not available"))}}if(this.persistenceMethod==="adapter"){if(this.persistenceAdapter!==null){this.persistenceAdapter.loadDatabase(this.filename,function loadDatabaseCallback(dbString){if(typeof dbString==="undefined"||dbString===null){console.warn("lokijs loadDatabase : Database not found");cFun("Database not found")}else{self.loadJSON(dbString);cFun(null)}})}else{cFun(new Error("persistenceAdapter not configured"))}}return}if(this.ENV==="NODEJS"){this.fs.readFile(this.filename,{encoding:"utf8"},function readFileCallback(err,data){if(err){return cFun(err,null)}if(!data.length){data=self.serialize()}self.loadJSON(data,options||{});cFun(null,data)})}else if(this.ENV==="BROWSER"){if(localStorageAvailable()){var data=localStorage.getItem(this.filename);self.loadJSON(data,options||{});cFun(null,data)}else{cFun(new Error("localStorage is not available"))}}else{cFun(new Error("unknown environment"))}};Loki.prototype.saveDatabase=function(callback){var cFun=callback||function(err){if(err){throw err}return},self=this;this.autosaveClearFlags();if(this.persistenceMethod!=null){if(this.persistenceMethod==="fs"){self.fs.writeFile(self.filename,self.serialize(),cFun)}if(this.persistenceMethod==="localStorage"){if(localStorageAvailable()){localStorage.setItem(self.filename,self.serialize());cFun(null)}else{cFun(new Error("localStorage is not available"))}}if(this.persistenceMethod==="adapter"){if(this.persistenceAdapter!==null){this.persistenceAdapter.saveDatabase(this.filename,self.serialize(),function saveDatabasecallback(){cFun(null)})}else{cFun(new Error("persistenceAdapter not configured"))}}return}if(this.ENV==="NODEJS"){self.fs.writeFile(self.filename,self.serialize(),cFun)}else if(this.ENV==="BROWSER"||this.ENV==="CORDOVA"){if(localStorageAvailable()){localStorage.setItem(self.filename,self.serialize());cFun(null)}else{cFun(new Error("localStorage is not available"))}}else{cFun(new Error("unknown environment"))}};Loki.prototype.save=Loki.prototype.saveDatabase;Loki.prototype.autosaveDirty=function(){for(var idx=0;idx<this.collections.length;idx++){if(this.collections[idx].dirty){return true}}return false};Loki.prototype.autosaveClearFlags=function(){for(var idx=0;idx<this.collections.length;idx++){this.collections[idx].dirty=false}};Loki.prototype.autosaveEnable=function(){this.autosave=true;var delay=5e3,self=this;if(typeof this.autosaveInterval!=="undefined"&&this.autosaveInterval!==null){delay=this.autosaveInterval}this.autosaveHandle=setInterval(function autosaveHandleInterval(){if(self.autosaveDirty()){self.saveDatabase()}},delay)};Loki.prototype.autosaveDisable=function(){if(typeof this.autosaveHandle!=="undefined"&&this.autosaveHandle!==null){clearInterval(this.autosaveHandle);this.autosaveHandle=null}};function Resultset(collection,queryObj,queryFunc,firstOnly){this.collection=collection;this.searchIsChained=!queryObj&&!queryFunc;this.filteredrows=[];this.filterInitialized=false;if(typeof queryObj!=="undefined"&&queryObj!==null){return this.find(queryObj,firstOnly)}if(typeof queryFunc!=="undefined"&&queryFunc!==null){return this.where(queryFunc)}return this}Resultset.prototype.toJSON=function(){var copy=this.copy();copy.collection=null;return copy};Resultset.prototype.limit=function(qty){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var rscopy=this.copy();rscopy.filteredrows=rscopy.filteredrows.slice(0,qty);return rscopy};Resultset.prototype.offset=function(pos){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var rscopy=this.copy();rscopy.filteredrows=rscopy.filteredrows.splice(pos,rscopy.filteredrows.length);return rscopy};Resultset.prototype.copy=function(){var result=new Resultset(this.collection,null,null);result.filteredrows=this.filteredrows.slice();result.filterInitialized=this.filterInitialized;return result};Resultset.prototype.branch=Resultset.prototype.copy;Resultset.prototype.sort=function(comparefun){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var wrappedComparer=function(userComparer,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return userComparer(obj1,obj2)}}(comparefun,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.simplesort=function(propname,isdesc){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}if(typeof isdesc==="undefined"){isdesc=false}var wrappedComparer=function(prop,desc,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return sortHelper(obj1[prop],obj2[prop],desc)}}(propname,isdesc,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.compoundeval=function(properties,obj1,obj2){var propertyCount=properties.length;if(propertyCount===0){throw new Error("Invalid call to compoundeval, need at least one property")}var isdesc=false;var firstProp=properties[0];if(typeof firstProp!=="string"){if(Array.isArray(firstProp)){isdesc=firstProp[1];firstProp=firstProp[0]}}if(obj1[firstProp]===obj2[firstProp]){if(propertyCount===1){return 0}else{return this.compoundeval(properties.slice(1),obj1,obj2,isdesc)}}return sortHelper(obj1[firstProp],obj2[firstProp],isdesc)};Resultset.prototype.compoundsort=function(properties){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var wrappedComparer=function(props,rslt){return function(a,b){var obj1=rslt.collection.data[a];var obj2=rslt.collection.data[b];return rslt.compoundeval(props,obj1,obj2)}}(properties,this);this.filteredrows.sort(wrappedComparer);return this};Resultset.prototype.calculateRange=function(op,prop,val){var rcd=this.collection.data;var index=this.collection.binaryIndices[prop].values;var min=0;var max=index.length-1;var mid=null;var lbound=0;var ubound=index.length-1;if(rcd.length==0){return[0,-1]}var minVal=rcd[index[min]][prop];var maxVal=rcd[index[max]][prop];switch(op){case"$eq":if(ltHelper(val,minVal)||gtHelper(val,maxVal)){return[0,-1]}break;case"$gt":if(gtHelper(val,maxVal,true)){return[0,-1]}break;case"$gte":if(gtHelper(val,maxVal)){return[0,-1]}break;case"$lt":if(ltHelper(val,minVal,true)){return[0,-1]}break;case"$lte":if(ltHelper(val,minVal)){return[0,-1]}break}while(min<max){mid=Math.floor((min+max)/2);if(ltHelper(rcd[index[mid]][prop],val)){min=mid+1}else{max=mid}}lbound=min;min=0;max=index.length-1;while(min<max){mid=Math.floor((min+max)/2);if(ltHelper(val,rcd[index[mid]][prop])){max=mid}else{min=mid+1}}ubound=max;var lval=rcd[index[lbound]][prop];var uval=rcd[index[ubound]][prop];switch(op){case"$eq":if(lval!==val){return[0,-1]}if(uval!==val){ubound--}return[lbound,ubound];case"$gt":if(ltHelper(uval,val,true)){return[0,-1]}return[ubound,rcd.length-1];case"$gte":if(ltHelper(lval,val)){return[0,-1]}return[lbound,rcd.length-1];case"$lt":return[0,lbound-1];case"$lte":if(uval!==val){ubound--}return[0,ubound];default:return[0,rcd.length-1]}};Resultset.prototype.findOr=function(expressionArray){var fri=0;var fr=null;if(this.filterInitialized){throw"OR op on already initialized resultset is not yet implemented, coming imminently"}for(var i=0;i<expressionArray.length;i++){var expResultset=this.collection.chain();expResultset.find(expressionArray[i]);expResultset.data();fr=expResultset.filteredrows;for(fri=0;fri<fr.length;fri++){if(this.filteredrows.indexOf(fr[fri])===-1){this.filteredrows.push(fr[fri])}}}this.filterInitialized=true;return this};Resultset.prototype.findAnd=function(expressionArray){for(var i=0;i<expressionArray.length;i++){this.find(expressionArray[i])}return this};Resultset.prototype.find=function(query,firstOnly){if(this.collection.data.length===0){if(this.searchIsChained){this.filteredrows=[];this.filterInitialized=true;return this}return[]}var queryObject=query||"getAll",property,value,operator,p,key,operators={$eq:LokiOps.$eq,$gt:LokiOps.$gt,$gte:LokiOps.$gte,$lt:LokiOps.$lt,$lte:LokiOps.$lte,$ne:LokiOps.$ne,$regex:LokiOps.$regex,$in:LokiOps.$in,$contains:LokiOps.$contains},searchByIndex=false,result=[],index=null,fun,t,i,len;if(typeof firstOnly==="undefined"){firstOnly=false}if(queryObject==="getAll"){if(this.searchIsChained){this.filteredrows=Object.keys(this.collection.data);return this}else{return this.collection.data}}var usingDotNotation=false;for(p in queryObject){if(queryObject.hasOwnProperty(p)){property=p;if(p==="$and"){if(this.searchIsChained){this.findAnd(queryObject[p]);return this}else{return this.collection.chain().findAnd(queryObject[p]).data()}}if(p==="$or"){if(this.searchIsChained){this.findOr(queryObject[p]);return this}else{return this.collection.chain().findOr(queryObject[p]).data()}}if(p.indexOf(".")!=-1){usingDotNotation=true}if(typeof queryObject[p]!=="object"){operator="$eq";value=queryObject[p]}else if(typeof queryObject[p]==="object"){for(key in queryObject[p]){if(queryObject[p].hasOwnProperty(key)){operator=key;value=queryObject[p][key]}}}else{throw"Do not know what you want to do."}break}}if(operator==="$regex")value=RegExp(value);if(this.collection.data===null){throw new TypeError}if((!this.searchIsChained||this.searchIsChained&&!this.filterInitialized)&&operator!=="$ne"&&operator!=="$regex"&&operator!=="$contains"&&operator!=="$in"&&this.collection.binaryIndices.hasOwnProperty(property)){this.collection.ensureIndex(property);searchByIndex=true;index=this.collection.binaryIndices[property]}fun=operators[operator];if(!this.searchIsChained){if(!searchByIndex){t=this.collection.data;i=t.length;if(firstOnly){while(i--){if(fun(t[i][property],value)){return t[i]}}return[]}else{if(usingDotNotation){var root,paths;while(i--){root=t[i];paths=property.split(".");paths.forEach(function(path){root=root[path]});if(fun(root,value)){result.push(t[i])}}}else{while(i--){if(fun(t[i][property],value)){result.push(t[i])}}}}}else{t=this.collection.data;len=t.length;var seg=this.calculateRange(operator,property,value,this);if(firstOnly){if(seg[1]!==-1){return this.data[seg[0]]}return[]}for(i=seg[0];i<=seg[1];i++){result.push(t[index.values[i]])}this.filteredrows=result}return result}else{if(this.filterInitialized){if(!searchByIndex){t=this.collection.data;i=this.filteredrows.length;if(usingDotNotation){var root,paths;while(i--){root=t[this.filteredrows[i]];paths=property.split(".");paths.forEach(function(path){root=root[path]});if(fun(root,value)){result.push(this.filteredrows[i])}}}else{while(i--){if(fun(t[this.filteredrows[i]][property],value)){result.push(this.filteredrows[i])}}}}else{t=index;i=this.filteredrows.length;while(i--){if(fun(t[this.filteredrows[i]],value)){result.push(this.filteredrows[i])}}}this.filteredrows=result;return this}else{if(!searchByIndex){t=this.collection.data;i=t.length;if(usingDotNotation){var root,paths;while(i--){root=t[i];paths=property.split(".");paths.forEach(function(path){root=root[path]});if(fun(root,value)){result.push(i)}}}else{while(i--){if(fun(t[i][property],value)){result.push(i)}}}}else{t=this.collection.data;var seg=this.calculateRange(operator,property,value,this);for(var idx=seg[0];idx<=seg[1];idx++){result.push(index.values[idx])}this.filteredrows=result}this.filteredrows=result;this.filterInitialized=true;return this}}};Resultset.prototype.where=function(fun){var viewFunction,result=[];if("function"===typeof fun){viewFunction=fun}else{throw"Argument is not a stored view or a function"}try{if(!this.searchIsChained){var i=this.collection.data.length;while(i--){if(viewFunction(this.collection.data[i])===true){result.push(this.collection.data[i])}}return result}else{if(this.filterInitialized){var i=this.filteredrows.length;while(i--){if(viewFunction(this.collection.data[this.filteredrows[i]])===true){result.push(this.filteredrows[i])}}this.filteredrows=result;return this}else{var i=this.collection.data.length;while(i--){if(viewFunction(this.collection.data[i])===true){result.push(i)}}this.filteredrows=result;this.filterInitialized=true;return this}}}catch(err){throw err}};Resultset.prototype.data=function(){var result=[];if(this.searchIsChained&&!this.filterInitialized){if(this.filteredrows.length===0){return this.collection.data}else{this.filterInitialized=true}}var data=this.collection.data,fr=this.filteredrows;var i,len=this.filteredrows.length;for(i=0;i<len;i++){result.push(data[fr[i]])}return result};Resultset.prototype.update=function(updateFunction){if(typeof updateFunction!=="function"){throw"Argument is not a function"}if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var len=this.filteredrows.length,rcd=this.collection.data;for(var idx=0;idx<len;idx++){updateFunction(rcd[this.filteredrows[idx]]);this.collection.update(rcd[this.filteredrows[idx]])}return this};Resultset.prototype.remove=function(){if(this.searchIsChained&&!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=Object.keys(this.collection.data)}var len=this.filteredrows.length;for(var idx=0;idx<len;idx++){this.collection.remove(this.filteredrows[idx])}this.filteredrows=[];return this};Resultset.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data().map(mapFunction))}catch(err){throw err}};function DynamicView(collection,name,persistent){this.collection=collection;this.name=name;this.persistent=false;if(typeof persistent!=="undefined")this.persistent=persistent;this.resultset=new Resultset(collection);this.resultdata=[];this.resultsdirty=false;this.cachedresultset=null;this.filterPipeline=[];this.sortFunction=null;this.sortCriteria=null;this.sortDirty=false;this.events={rebuild:[]}}DynamicView.prototype=new LokiEventEmitter;DynamicView.prototype.rematerialize=function(options){var fpl,fpi,idx;options=options||{};this.resultdata=[];this.resultsdirty=true;this.resultset=new Resultset(this.collection);if(this.sortFunction||this.sortCriteria){this.sortDirty=true}if(options.hasOwnProperty("removeWhereFilters")){fpl=this.filterPipeline.length;fpi=fpl;while(fpi--){if(this.filterPipeline[fpi].type==="where"){if(fpi!==this.filterPipeline.length-1){this.filterPipeline[fpi]=this.filterPipeline[this.filterPipeline.length-1]}this.filterPipeline.length--}}}var ofp=this.filterPipeline;this.filterPipeline=[];fpl=ofp.length;for(idx=0;idx<fpl;idx++){this.applyFind(ofp[idx].val)}this.data();this.emit("rebuild",this);return this};DynamicView.prototype.branchResultset=function(){return this.resultset.copy()};DynamicView.prototype.toJSON=function(){var copy=new DynamicView(this.collection,this.name,this.persistent);copy.resultset=this.resultset;copy.resultdata=[];copy.resultsdirty=true;copy.filterPipeline=this.filterPipeline;copy.sortFunction=this.sortFunction;copy.sortCriteria=this.sortCriteria;copy.sortDirty=this.sortDirty;copy.collection=null;return copy};DynamicView.prototype.applySort=function(comparefun){this.sortFunction=comparefun;this.sortCriteria=null;this.resultset.sort(comparefun);this.sortDirty=false;return this};DynamicView.prototype.applySimpleSort=function(propname,isdesc){if(typeof isdesc==="undefined"){isdesc=false}this.sortCriteria=[[propname,isdesc]];this.sortFunction=null;this.resultset.simplesort(propname,isdesc);this.sortDirty=false;return this};DynamicView.prototype.applySortCriteria=function(criteria){this.sortCriterial=criteria;this.sortFunction=null;this.resultset.compoundsort(criteria);this.sortDirty=false;return this};DynamicView.prototype.startTransaction=function(){this.cachedresultset=this.resultset.copy();return this};DynamicView.prototype.commit=function(){this.cachedresultset=null;return this};DynamicView.prototype.rollback=function(){this.resultset=this.cachedresultset;if(this.persistent){this.resultdata=this.resultset.data();this.emit("rebuild",this)}return this};DynamicView.prototype.applyFind=function(query){this.filterPipeline.push({type:"find",val:query});this.resultset.find(query);if(this.sortFunction||this.sortCriteria){this.sortDirty=true}if(this.persistent){this.resultsdirty=true}return this};DynamicView.prototype.applyWhere=function(fun){this.filterPipeline.push({type:"where",val:fun});this.resultset.where(fun);if(this.sortFunction||this.sortCriteria){this.sortDirty=true}if(this.persistent){this.resultsdirty=true}return this};DynamicView.prototype.data=function(){if(this.sortDirty){if(this.sortFunction){this.resultset.sort(this.sortFunction)}if(this.sortCriteria){this.resultset.compoundsort(this.sortCriteria)}this.sortDirty=false;if(this.persistent){this.resultsdirty=true}}if(!this.persistent){if(!this.resultset.filterInitialized){this.emit("rebuild",this)}return this.resultset.data()}if(this.resultsdirty){this.resultdata=this.resultset.data();this.resultsdirty=false;this.emit("rebuild",this)}return this.resultdata};DynamicView.prototype.evaluateDocument=function(objIndex){var ofr=this.resultset.filteredrows;var oldPos=ofr.indexOf(objIndex);var oldlen=ofr.length;var evalResultset=new Resultset(this.collection);evalResultset.filteredrows=[objIndex];evalResultset.filterInitialized=true;for(var idx=0;idx<this.filterPipeline.length;idx++){switch(this.filterPipeline[idx].type){case"find":evalResultset.find(this.filterPipeline[idx].val);break;case"where":evalResultset.where(this.filterPipeline[idx].val);break}}var newPos=evalResultset.filteredrows.length===0?-1:0;if(oldPos==-1&&newPos==-1)return;if(oldPos===-1&&newPos!==-1){ofr.push(objIndex);if(this.persistent){this.resultdata.push(this.collection.data[objIndex])}if(this.sortFunction||this.sortCriteria){this.sortDirty=true}return}if(oldPos!==-1&&newPos===-1){if(oldPos<oldlen-1){ofr[oldPos]=ofr[oldlen-1];ofr.length=oldlen-1;if(this.persistent){this.resultdata[oldPos]=this.resultdata[oldlen-1];this.resultdata.length=oldlen-1}}else{ofr.length=oldlen-1;if(this.persistent){this.resultdata.length=oldlen-1}}return}if(oldPos!==-1&&newPos!==-1){if(this.persistent){this.resultdata[oldPos]=this.collection.data[objIndex]}if(this.sortFunction||this.sortCriteria){this.sortDirty=true}return}};DynamicView.prototype.removeDocument=function(objIndex){var ofr=this.resultset.filteredrows;var oldPos=ofr.indexOf(objIndex);var oldlen=ofr.length;if(oldPos!==-1){if(oldPos<oldlen-1){ofr[oldPos]=ofr[oldlen-1];ofr.length=oldlen-1;this.resultdata[oldPos]=this.resultdata[oldlen-1];this.resultdata.length=oldlen-1}else{ofr.length=oldlen-1;this.resultdata.length=oldlen-1}}};DynamicView.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data().map(mapFunction))}catch(err){throw err}};function Collection(name,options){this.name=name;this.data=[];this.idIndex=[];this.binaryIndices={};this.objType=name;this.dirty=true;this.cachedIndex=null;this.cachedBinaryIndex=null;this.cachedData=null;var self=this;options=options||{};this.transactional=options.hasOwnProperty("transactional")?options.transactional:false;this.cloneObjects=options.hasOwnProperty("clone")?options.clone:false;this.asyncListeners=options.hasOwnProperty("asyncListeners")?options.asyncListeners:true;this.disableChangesApi=options.hasOwnProperty("disableChangesApi")?options.disableChangesApi:true;this.maxId=0;this.DynamicViews=[];this.events={insert:[],update:[],close:[],flushbuffer:[],error:[],"delete":[],warning:[]};this.changes=[];this.ensureId();var indices;if(options){indices=options.indices||[]}else{indices=[]}for(var idx=0;idx<indices.length;idx++){this.ensureIndex(indices[idx])}function createChange(name,op,obj){self.changes.push({name:name,operation:op,obj:JSON.parse(JSON.stringify(obj))})}function flushChanges(){self.changes=[]}this.getChanges=function(){return self.changes};this.flushChanges=flushChanges;function insertMeta(obj){if(!obj){return}if(!obj.meta){obj.meta={}}obj.meta.created=(new Date).getTime();obj.meta.revision=0}function updateMeta(obj){if(!obj){return}obj.meta.updated=(new Date).getTime();obj.meta.revision+=1}function createInsertChange(obj){createChange(self.name,"I",obj)}function createUpdateChange(obj){createChange(self.name,"U",obj)}function insertMetaWithChange(obj){insertMeta(obj);createInsertChange(obj)}function updateMetaWithChange(obj){updateMeta(obj);createUpdateChange(obj)}var insertHandler,updateHandler;function setHandlers(){insertHandler=self.disableChangesApi?insertMeta:insertMetaWithChange;updateHandler=self.disableChangesApi?updateMeta:updateMetaWithChange}setHandlers();this.setChangesApi=function(enabled){self.disableChangesApi=!enabled;setHandlers()};this.on("insert",function insertCallback(obj){insertHandler(obj)});this.on("update",function updateCallback(obj){updateHandler(obj)});this.on("delete",function deleteCallback(obj){if(!self.disableChangesApi){createChange(self.name,"R",obj)}});this.on("warning",console.warn);flushChanges()}Collection.prototype=new LokiEventEmitter;Collection.prototype.ensureIndex=function(property,force){if(typeof force==="undefined"){force=false}if(property===null||property===undefined){throw"Attempting to set index without an associated property"}if(this.binaryIndices.hasOwnProperty(property)&&!force){if(!this.binaryIndices[property].dirty)return}this.binaryIndices[property]={name:property,dirty:true,values:[]};var index,len=this.data.length,i=0;index=this.binaryIndices[property];for(i;i<len;i+=1){index.values.push(i)}var wrappedComparer=function(prop,coll){return function(a,b){var obj1=coll.data[a];var obj2=coll.data[b];if(obj1[prop]===obj2[prop])return 0;if(gtHelper(obj1[prop],obj2[prop]))return 1;if(ltHelper(obj1[prop],obj2[prop]))return-1}}(property,this);index.values.sort(wrappedComparer);index.dirty=false;this.dirty=true};Collection.prototype.ensureAllIndexes=function(force){var objKeys=Object.keys(this.binaryIndices);
var i=objKeys.length;while(i--){this.ensureIndex(objKeys[i],force)}};Collection.prototype.flagBinaryIndexesDirty=function(){var objKeys=Object.keys(this.binaryIndices);var i=objKeys.length;while(i--){this.binaryIndices[objKeys[i]].dirty=true}};Collection.prototype.ensureId=function(){var len=this.data.length,i=0;this.idIndex=[];for(i;i<len;i+=1){this.idIndex.push(this.data[i].$loki)}};Collection.prototype.ensureIdAsync=function(callback){this.async(function(){this.ensureId()},callback)};Collection.prototype.addDynamicView=function(name,persistent){var dv=new DynamicView(this,name,persistent);this.DynamicViews.push(dv);return dv};Collection.prototype.removeDynamicView=function(name){for(var idx=0;idx<this.DynamicViews.length;idx++){if(this.DynamicViews[idx].name===name){this.DynamicViews.splice(idx,1)}}};Collection.prototype.getDynamicView=function(name){for(var idx=0;idx<this.DynamicViews.length;idx++){if(this.DynamicViews[idx].name===name){return this.DynamicViews[idx]}}return null};Collection.prototype.findAndUpdate=function(filterFunction,updateFunction){var results=this.where(filterFunction),i=0,obj;try{for(i;i<results.length;i++){obj=updateFunction(results[i]);this.update(obj)}}catch(err){this.rollback();console.error(err.message)}};Collection.prototype.insert=function(doc){var self=this;var obj;if(Array.isArray(doc)){doc.forEach(function(d){if(self.clone){obj=JSON.parse(JSON.stringify(d))}else{obj=d}if(typeof obj.meta==="undefined"){obj.meta={revision:0,created:0}}self.add(obj);self.emit("insert",obj)});return obj}else{if(typeof doc!=="object"){throw new TypeError("Document needs to be an object");return}if(!doc){var error=new Error("Object cannot be null");this.emit("error",error);throw error}if(self.clone){obj=JSON.parse(JSON.stringify(doc))}else{obj=doc}if(typeof doc.meta==="undefined"){obj.meta={revision:0,created:0}}self.add(obj);self.emit("insert",obj);return obj}};Collection.prototype.clear=function(){this.data=[];this.idIndex=[];this.binaryIndices={};this.cachedIndex=null;this.cachedData=null;this.maxId=0;this.DynamicViews=[];this.dirty=true};Collection.prototype.update=function(doc){if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}if(Array.isArray(doc)){var k=0,len=doc.length;for(k;k<len;k+=1){this.update(doc[k])}return}if(!doc.hasOwnProperty("$loki")){throw"Trying to update unsynced document. Please save the document first by using insert() or addMany()"}try{this.startTransaction();var i,arr=this.get(doc.$loki,true),obj,position;if(!arr){throw new Error("Trying to update a document not in collection.")}obj=arr[0];position=arr[1];this.data[position]=doc;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].evaluateDocument(position)}this.idIndex[position]=obj.$loki;this.commit();this.dirty=true;this.emit("update",doc)}catch(err){this.rollback();console.error(err.message);this.emit("error",err);throw err}};Collection.prototype.add=function(obj){var i,dvlen=this.DynamicViews.length;if("object"!==typeof obj){throw"Object being added needs to be an object"}if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}if(typeof obj.$loki!=="undefined"){throw"Document is already in collection, please use update()"}try{this.startTransaction();this.maxId++;var i;if(isNaN(this.maxId)){this.maxId=this.data[this.data.length-1].$loki+1}obj.$loki=this.maxId;obj.meta.version=0;this.data.push(obj);for(i=0;i<dvlen;i++){this.DynamicViews[i].evaluateDocument(this.data.length-1)}this.idIndex.push(obj.$loki);this.commit();this.dirty=true;return obj}catch(err){this.rollback();console.error(err.message)}};Collection.prototype.removeWhere=function(query){var list;if(typeof query==="function"){list=this.data.filter(query)}else{list=new Resultset(this,query)}var len=list.length;while(len--){this.remove(list[len])}};Collection.prototype.remove=function(doc){var self=this;if(typeof doc==="number"){doc=this.get(doc)}if("object"!==typeof doc){throw new Error("Parameter is not an object")}if(Array.isArray(doc)){var k=0,len=doc.length;for(k;k<len;k+=1){this.remove(doc[k])}return}if(!doc.hasOwnProperty("$loki")){throw new Error("Object is not a document stored in the collection")}if(Object.keys(this.binaryIndices).length>0){this.flagBinaryIndexesDirty()}try{this.startTransaction();var arr=this.get(doc.$loki,true),position=arr[1],i;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].removeDocument(position)}this.data.splice(position,1);this.idIndex.splice(position,1);this.commit();this.dirty=true;this.emit("delete")}catch(err){this.rollback();console.error(err.message);this.emit("error",err)}};Collection.prototype.get=function(id,returnPosition){var retpos=returnPosition||false,data=this.idIndex,max=data.length-1,min=0,mid=Math.floor(min+(max-min)/2);if(isNaN(id)){id=parseInt(id);if(isNaN(id)){throw"Passed id is not an integer"}}while(data[min]<data[max]){mid=Math.floor((min+max)/2);if(data[mid]<id){min=mid+1}else{max=mid}}if(max===min&&data[min]===id){if(retpos){return[this.data[min],min]}return this.data[min]}return null};Collection.prototype.findOne=function(query){var result=new Resultset(this,query,null,true);if(Array.isArray(result)&&result.length===0){return null}else{return result}};Collection.prototype.chain=function(){return new Resultset(this,null,null)};Collection.prototype.find=function(query){if(typeof query==="undefined"){query="getAll"}return new Resultset(this,query,null)};Collection.prototype.findOneUnindexed=function(prop,value){var i=this.data.length,doc;while(i--){if(this.data[i][prop]===value){doc=this.data[i];return doc}}return null};Collection.prototype.startTransaction=function(){if(this.transactional){this.cachedData=clone(this.data,"parse-stringify");this.cachedIndex=this.idIndex;this.cachedBinaryIndex=this.binaryIndices;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].startTransaction()}}};Collection.prototype.commit=function(){if(this.transactional){this.cachedData=null;this.cachedIndex=null;this.cachedBinaryIndices=null;for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].commit()}}};Collection.prototype.rollback=function(){if(this.transactional){if(this.cachedData!==null&&this.cachedIndex!==null){this.data=this.cachedData;this.idIndex=this.cachedIndex;this.binaryIndices=this.cachedBinaryIndex}for(var idx=0;idx<this.DynamicViews.length;idx++){this.DynamicViews[idx].rollback()}}};Collection.prototype.async=function(fun,callback){setTimeout(function(){if(typeof fun==="function"){fun();callback()}else{throw"Argument passed for async execution is not a function"}},0)};Collection.prototype.where=function(fun){return new Resultset(this,null,fun)};Collection.prototype.mapReduce=function(mapFunction,reduceFunction){try{return reduceFunction(this.data.map(mapFunction))}catch(err){throw err}};Collection.prototype.no_op=function(){return};Loki.Collection=Collection;return Loki}()});
!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,i){return t===e?i?!0:!1:void 0===t?!0:void 0===e?!1:null===t?!0:null===e?!1:e>t}function e(t,e,i){return t===e?i?!0:!1:void 0===t?!1:void 0===e?!0:null===t?!1:null===e?!0:t>e}function i(i,n,s){return i===n?0:s?t(i,n)?1:-1:e(i,n)?1:-1}function n(t,e){var i,n=e||"parse-stringify";return"parse-stringify"===n&&(i=JSON.parse(JSON.stringify(t))),i}function s(){try{return"localStorage"in window&&null!==window.localStorage}catch(t){return!1}}function r(){}function o(t,e){t.apply(null,e)}function a(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,this.events={init:[],flushChanges:[],close:[],changes:[],warning:[]};var i=function(){return"undefined"==typeof window?"NODEJS":"undefined"!=typeof global&&global.window?"NODEJS":"undefined"!=typeof document?-1===document.URL.indexOf("http://")&&-1===document.URL.indexOf("https://")?"CORDOVA":"BROWSER":"CORDOVA"};this.ENV=e&&e.hasOwnProperty("env")?e.env:i(),"undefined"===this.ENV&&(this.ENV="NODEJS"),"NODEJS"===this.ENV&&(this.fs=require("fs")),"undefined"!=typeof e&&this.configureOptions(e,!0),this.on("init",this.clearChanges)}function l(t,e,i,n){return this.collection=t,this.searchIsChained=!e&&!i,this.filteredrows=[],this.filterInitialized=!1,"undefined"!=typeof e&&null!==e?this.find(e,n):"undefined"!=typeof i&&null!==i?this.where(i):this}function h(t,e,i){this.collection=t,this.name=e,this.persistent=!1,"undefined"!=typeof i&&(this.persistent=i),this.resultset=new l(t),this.resultdata=[],this.resultsdirty=!1,this.cachedresultset=null,this.filterPipeline=[],this.sortFunction=null,this.sortCriteria=null,this.sortDirty=!1,this.events={rebuild:[]}}function c(t,e){function i(t,e,i){u.changes.push({name:t,operation:e,obj:JSON.parse(JSON.stringify(i))})}function n(){u.changes=[]}function s(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){s(t),o(t)}function h(t){r(t),a(t)}function c(){p=u.disableChangesApi?s:l,y=u.disableChangesApi?r:h}this.name=t,this.data=[],this.idIndex=[],this.binaryIndices={},this.objType=t,this.dirty=!0,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:!1,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=[];if(e&&e.indices)if("[object Array]"===Object.prototype.toString.call(e.indices))d=e.indices;else{if("string"!=typeof e.indices)throw new TypeError("Indices needs to be a string or an array of strings");d=[e.indices]}for(var f=0;f<d.length;f++)this.ensureIndex(d[f]);this.getChanges=function(){return u.changes},this.flushChanges=n;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),n()}function u(t,e,i){for(var n,s,r=0,o=t.length;o>r;){if(s=(r+o)/2|0,n=i.apply(null,[e,t[s]]),0==n)return{found:!0,index:s};0>n?o=s:r=s+1}return{found:!1,index:o}}function d(t){return function(e,i){return u(e,i,t)}}function f(){}{var p={copyProperties:function(t,e){var i;for(i in t)e[i]=t[i]}},y={$eq:function(t,e){return t===e},$gt:function(t,i){return e(t,i)},$gte:function(t,i){return e(t,i,!0)},$lt:function(e,i){return t(e,i)},$lte:function(e,i){return t(e,i,!0)},$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){var i=function(){return!0};return Array.isArray(e)||(e=[e]),Array.isArray(t)?i=function(e){return-1!==t.indexOf(e)}:"string"==typeof t?i=function(e){return-1!==t.indexOf(e)}:t&&"object"==typeof t&&(i=function(e){return t.hasOwnProperty(e)}),e.reduce(function(t,e){return t?i(e):t},!0)}};"object"==typeof exports?require("fs"):!1}return r.prototype.events={},r.prototype.asyncListeners=!1,r.prototype.on=function(t,e){var i=this.events[t];return i||(i=this.events[t]=[]),i.push(e)-1},r.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(){o(t,e)},1):o(t,e)})},r.prototype.removeListener=function(t,e){this.events[t]&&this.events[t].splice(e,1)},a.prototype=new r,a.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())},a.prototype.anonym=function(t,e){var i=new c("anonym",e);return i.insert(t),i},a.prototype.addCollection=function(t,e){var i=new c(t,e);return this.collections.push(i),i},a.prototype.loadCollection=function(t){if(!t.name)throw new Error("Collection must be have a name property to be loaded");this.collections.push(t)},a.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},a.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},a.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"},a.prototype.getName=function(){return this.name},a.prototype.serializeReplacer=function(t,e){switch(t){case"autosaveHandle":return null;default:return e}},a.prototype.serialize=function(){return JSON.stringify(this,this.serializeReplacer)},a.prototype.toJson=a.prototype.serialize,a.prototype.loadJSON=function(t,e){var i,n,s,r,o=JSON.parse(t),a=0,l=o.collections.length,h=!1;for(this.name=o.name,this.databaseVersion=1,o.hasOwnProperty("databaseVersion")&&(this.databaseVersion=o.databaseVersion),this.databaseVersion!==this.engineVersion&&(h=!0),this.collections=[],a;l>a;a+=1){if(i=o.collections[a],n=this.addCollection(i.name),s=i.data.length,r=0,e&&e.hasOwnProperty(i.name)){var c=e[i.name].inflate?e[i.name].inflate:p.copyProperties;for(r;s>r;r++){var u=new e[i.name].proto;c(i.data[r],u),n.data[r]=u}}else for(r;s>r;r++)n.data[r]=i.data[r];if(h&&1.1==this.engineVersion){if(n.transactional=!1,n.cloneObjects=!1,n.asyncListeners=!0,n.disableChangesApi=!0,console.warn("upgrading database, loki id is now called '$loki' instead of 'id'"),n.data.length>0&&!n.data[0].hasOwnProperty("$loki"))for(var d=n.data.length,f=null,y=0;d>y;y++)f=n.data[y],f.$loki=f.id,delete f.id,f.hasOwnProperty.originalId&&(f.id=f.originalId)}else n.transactional=i.transactional,n.asyncListeners=i.asyncListeners,n.disableChangesApi=i.disableChangesApi,n.cloneObjects=i.cloneObjects;if(n.maxId=0===i.data.length?0:i.maxId,n.idIndex=i.idIndex,"undefined"!=typeof i.indices&&(n.idIndex=i.indices.id),"undefined"!=typeof i.binaryIndices&&(n.binaryIndices=i.binaryIndices),n.ensureId(),"undefined"!=typeof i.DynamicViews)for(var y=0;y<i.DynamicViews.length;y++){var v=i.DynamicViews[y],g=n.addDynamicView(v.name,v.persistent);if(g.resultdata=v.resultdata,g.resultsdirty=v.resultsdirty,g.filterPipeline=v.filterPipeline,h&&"undefined"!=typeof v.sortColumn&&null!=v.sortColumn){var w=!1;"undefined"!=typeof v.sortColumnDesc&&(w=v.sortColumnDesc),g.sortCriteria=[v.sortColumn,w]}else g.sortCriteria=v.sortCriteria;g.sortFunction=null,g.sortDirty=v.sortDirty,g.resultset.filteredrows=v.resultset.filteredrows,g.resultset.searchIsChained=v.resultset.searchIsChained,g.resultset.filterInitialized=v.resultset.filterInitialized,g.rematerialize({removeWhereFilters:!0})}}},a.prototype.close=function(t){this.autosave&&(this.autosaveDisable(),this.autosaveDirty()&&this.saveDatabase()),t&&this.on("close",t),this.emit("close")},a.prototype.generateChangesNotification=function(t){function e(t){return t.name}var i=[],n=t||this.collections.map(e);return this.collections.forEach(function(t){-1!==n.indexOf(e(t))&&(i=i.concat(t.getChanges()))}),i},a.prototype.serializeChanges=function(t){return JSON.stringify(this.generateChangesNotification(t))},a.prototype.clearChanges=function(){this.collections.forEach(function(t){t.flushChanges&&t.flushChanges()})},a.prototype.loadDatabase=function(t,e){var i=e||function(t){if(t)throw t},n=this;if(null!=this.persistenceMethod){if("fs"===this.persistenceMethod&&this.fs.readFile(this.filename,{encoding:"utf8"},function(e,s){return e?i(e,null):(n.loadJSON(s,t||{}),void i(null,s))}),"localStorage"===this.persistenceMethod)if(s()){var r=localStorage.getItem(this.filename);n.loadJSON(r,t||{}),i(null,r)}else i(new Error("localStorage is not available"));return 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"),i("Database not found")):(n.loadJSON(t),i(null))}):i(new Error("persistenceAdapter not configured"))))}if("NODEJS"===this.ENV)this.fs.readFile(this.filename,{encoding:"utf8"},function(e,s){return e?i(e,null):(s.length||(s=n.serialize()),n.loadJSON(s,t||{}),void i(null,s))});else if("BROWSER"===this.ENV)if(s()){var r=localStorage.getItem(this.filename);n.loadJSON(r,t||{}),i(null,r)}else i(new Error("localStorage is not available"));else i(new Error("unknown environment"))},a.prototype.saveDatabase=function(t){var e=t||function(t){if(t)throw t},i=this;return this.autosaveClearFlags(),null!=this.persistenceMethod?("fs"===this.persistenceMethod&&i.fs.writeFile(i.filename,i.serialize(),e),"localStorage"===this.persistenceMethod&&(s()?(localStorage.setItem(i.filename,i.serialize()),e(null)):e(new Error("localStorage is not available"))),void("adapter"===this.persistenceMethod&&(null!==this.persistenceAdapter?this.persistenceAdapter.saveDatabase(this.filename,i.serialize(),function(){e(null)}):e(new Error("persistenceAdapter not configured"))))):void("NODEJS"===this.ENV?i.fs.writeFile(i.filename,i.serialize(),e):"BROWSER"===this.ENV||"CORDOVA"===this.ENV?s()?(localStorage.setItem(i.filename,i.serialize()),e(null)):e(new Error("localStorage is not available")):e(new Error("unknown environment")))},a.prototype.save=a.prototype.saveDatabase,a.prototype.autosaveDirty=function(){for(var t=0;t<this.collections.length;t++)if(this.collections[t].dirty)return!0;return!1},a.prototype.autosaveClearFlags=function(){for(var t=0;t<this.collections.length;t++)this.collections[t].dirty=!1},a.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)},a.prototype.autosaveDisable=function(){"undefined"!=typeof this.autosaveHandle&&null!==this.autosaveHandle&&(clearInterval(this.autosaveHandle),this.autosaveHandle=null)},l.prototype.toJSON=function(){var t=this.copy();return t.collection=null,t},l.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},l.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},l.prototype.copy=function(){var t=new l(this.collection,null,null);return t.filteredrows=this.filteredrows.slice(),t.filterInitialized=this.filterInitialized,t},l.prototype.branch=l.prototype.copy,l.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,n){var s=e.collection.data[i],r=e.collection.data[n];return t(s,r)}}(t,this);return this.filteredrows.sort(e),this},l.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 n=function(t,e,n){return function(s,r){var o=n.collection.data[s],a=n.collection.data[r];return i(o[t],a[t],e)}}(t,e,this);return this.filteredrows.sort(n),this},l.prototype.compoundeval=function(t,e,n){var s=t.length;if(0===s)throw new Error("Invalid call to compoundeval, need at least one property");var r=!1,o=t[0];return"string"!=typeof o&&Array.isArray(o)&&(r=o[1],o=o[0]),e[o]===n[o]?1===s?0:this.compoundeval(t.slice(1),e,n,r):i(e[o],n[o],r)},l.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,n){var s=e.collection.data[i],r=e.collection.data[n];return e.compoundeval(t,s,r)}}(t,this);return this.filteredrows.sort(e),this},l.prototype.calculateRange=function(i,n,s){var r=this.collection.data,o=this.collection.binaryIndices[n].values,a=0,l=o.length-1,h=null,c=0,u=o.length-1;if(0==r.length)return[0,-1];var d=r[o[a]][n],f=r[o[l]][n];switch(i){case"$eq":if(t(s,d)||e(s,f))return[0,-1];break;case"$gt":if(e(s,f,!0))return[0,-1];break;case"$gte":if(e(s,f))return[0,-1];break;case"$lt":if(t(s,d,!0))return[0,-1];break;case"$lte":if(t(s,d))return[0,-1]}for(;l>a;)h=Math.floor((a+l)/2),t(r[o[h]][n],s)?a=h+1:l=h;for(c=a,a=0,l=o.length-1;l>a;)h=Math.floor((a+l)/2),t(s,r[o[h]][n])?l=h:a=h+1;u=l;var p=r[o[c]][n],y=r[o[u]][n];switch(i){case"$eq":return p!==s?[0,-1]:(y!==s&&u--,[c,u]);case"$gt":return t(y,s,!0)?[0,-1]:[u,r.length-1];case"$gte":return t(p,s)?[0,-1]:[c,r.length-1];case"$lt":return 0===c&&t(p,s)?[0,0]:[0,c-1];case"$lte":return y!==s&&u--,0===u&&t(y,s)?[0,0]:[0,u];default:return[0,r.length-1]}},l.prototype.findOr=function(t){var e=0,i=0,n=null,s=[],r=null;if(this.filterInitialized){for(s=[],i=0;i<t.length;i++)for(r=this.branch(),r.find(t[i]),r.data(),n=r.filteredrows,e=0;e<n.length;e++)-1===s.indexOf(n[e])&&s.push(n[e]);this.filteredrows=s}else for(i=0;i<t.length;i++)for(r=this.collection.chain(),r.find(t[i]),r.data(),n=r.filteredrows,e=0;e<n.length;e++)-1===this.filteredrows.indexOf(n[e])&&this.filteredrows.push(n[e]);return this.filterInitialized=!0,this},l.prototype.findAnd=function(t){for(var e=0;e<t.length;e++)this.find(t[e]);return this},l.prototype.find=function(t,e){if(0===this.collection.data.length)return this.searchIsChained?(this.filteredrows=[],this.filterInitialized=!0,this):[];var i,n,s,r,o,a,l,h,c,u=t||"getAll",d={$eq:y.$eq,$gt:y.$gt,$gte:y.$gte,$lt:y.$lt,$lte:y.$lte,$ne:y.$ne,$regex:y.$regex,$in:y.$in,$contains:y.$contains},f=!1,p=[],v=null;if("undefined"==typeof e&&(e=!1),"getAll"===u)return this.searchIsChained?(this.filteredrows=Object.keys(this.collection.data),this):this.collection.data;var g=!1;for(r in u)if(u.hasOwnProperty(r)){if(i=r,"$and"===r)return this.searchIsChained?(this.findAnd(u[r]),this):this.collection.chain().findAnd(u[r]).data();if("$or"===r)return this.searchIsChained?(this.findOr(u[r]),this):this.collection.chain().findOr(u[r]).data();if(-1!=r.indexOf(".")&&(g=!0),"object"!=typeof u[r])s="$eq",n=u[r];else{if("object"!=typeof u[r])throw"Do not know what you want to do.";for(o in u[r])u[r].hasOwnProperty(o)&&(s=o,n=u[r][o])}break}if("$regex"===s&&(n=RegExp(n)),null===this.collection.data)throw new TypeError;if((!this.searchIsChained||this.searchIsChained&&!this.filterInitialized)&&"$ne"!==s&&"$regex"!==s&&"$contains"!==s&&"$in"!==s&&this.collection.binaryIndices.hasOwnProperty(i)&&(this.collection.ensureIndex(i),f=!0,v=this.collection.binaryIndices[i]),a=d[s],this.searchIsChained){if(this.filterInitialized){if(f)for(l=v,h=this.filteredrows.length;h--;)a(l[this.filteredrows[h]],n)&&p.push(this.filteredrows[h]);else if(l=this.collection.data,h=this.filteredrows.length,g)for(var w,m;h--;)w=l[this.filteredrows[h]],m=i.split("."),m.forEach(function(t){w=w[t]}),a(w,n)&&p.push(this.filteredrows[h]);else for(;h--;)a(l[this.filteredrows[h]][i],n)&&p.push(this.filteredrows[h]);return this.filteredrows=p,this}if(f){l=this.collection.data;for(var b=this.calculateRange(s,i,n,this),I=b[0];I<=b[1];I++)p.push(v.values[I]);this.filteredrows=p}else if(l=this.collection.data,h=l.length,g)for(var w,m;h--;)w=l[h],m=i.split("."),m.forEach(function(t){w=w[t]}),a(w,n)&&p.push(h);else for(;h--;)a(l[h][i],n)&&p.push(h);return this.filteredrows=p,this.filterInitialized=!0,this}if(f){l=this.collection.data,c=l.length;var b=this.calculateRange(s,i,n,this);if(e)return-1!==b[1]?l[v.values[b[0]]]:[];for(h=b[0];h<=b[1];h++)p.push(l[v.values[h]]);this.filteredrows=p}else{if(l=this.collection.data,h=l.length,e){for(;h--;)if(a(l[h][i],n))return l[h];return[]}if(g)for(var w,m;h--;)w=l[h],m=i.split("."),m.forEach(function(t){w=w[t]}),a(w,n)&&p.push(l[h]);else for(;h--;)a(l[h][i],n)&&p.push(l[h])}return p},l.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 n=this.filteredrows.length;n--;)e(this.collection.data[this.filteredrows[n]])===!0&&i.push(this.filteredrows[n]);return this.filteredrows=i,this}for(var n=this.collection.data.length;n--;)e(this.collection.data[n])===!0&&i.push(n);return this.filteredrows=i,this.filterInitialized=!0,this}for(var n=this.collection.data.length;n--;)e(this.collection.data[n])===!0&&i.push(this.collection.data[n]);return i}catch(s){throw s}},l.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,n=this.filteredrows,s=this.filteredrows.length;for(e=0;s>e;e++)t.push(i[n[e]]);return t},l.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,n=0;e>n;n++)t(i[this.filteredrows[n]]),this.collection.update(i[this.filteredrows[n]]);return this},l.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},l.prototype.mapReduce=function(t,e){try{return e(this.data().map(t))}catch(i){throw i}},h.prototype=new r,h.prototype.rematerialize=function(t){var e,i,n;if(t=t||{},this.resultdata=[],this.resultsdirty=!0,this.resultset=new l(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 s=this.filterPipeline;for(this.filterPipeline=[],e=s.length,n=0;e>n;n++)this.applyFind(s[n].val);return this.data(),this.emit("rebuild",this),this},h.prototype.branchResultset=function(){return this.resultset.copy()},h.prototype.toJSON=function(){var t=new h(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},h.prototype.applySort=function(t){return this.sortFunction=t,this.sortCriteria=null,this.resultset.sort(t),this.sortDirty=!1,this},h.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},h.prototype.applySortCriteria=function(t){return this.sortCriterial=t,this.sortFunction=null,this.resultset.compoundsort(t),this.sortDirty=!1,this},h.prototype.startTransaction=function(){return this.cachedresultset=this.resultset.copy(),this},h.prototype.commit=function(){return this.cachedresultset=null,this},h.prototype.rollback=function(){return this.resultset=this.cachedresultset,this.persistent&&(this.resultdata=this.resultset.data(),this.emit("rebuild",this)),this},h.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},h.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},h.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())},h.prototype.evaluateDocument=function(t){var e=this.resultset.filteredrows,i=e.indexOf(t),n=e.length,s=new l(this.collection);s.filteredrows=[t],s.filterInitialized=!0;for(var r=0;r<this.filterPipeline.length;r++)switch(this.filterPipeline[r].type){case"find":s.find(this.filterPipeline[r].val);break;case"where":s.where(this.filterPipeline[r].val)}var o=0===s.filteredrows.length?-1:0;return-1!=i||-1!=o?-1===i&&-1!==o?(e.push(t),this.persistent&&this.resultdata.push(this.collection.data[t]),void((this.sortFunction||this.sortCriteria)&&(this.sortDirty=!0))):-1!==i&&-1===o?void(n-1>i?(e[i]=e[n-1],e.length=n-1,this.persistent&&(this.resultdata[i]=this.resultdata[n-1],this.resultdata.length=n-1)):(e.length=n-1,this.persistent&&(this.resultdata.length=n-1))):-1!==i&&-1!==o?(this.persistent&&(this.resultdata[i]=this.collection.data[t]),void((this.sortFunction||this.sortCriteria)&&(this.sortDirty=!0))):void 0:void 0},h.prototype.removeDocument=function(t){var e,i=this.resultset.filteredrows,n=i.indexOf(t),s=i.length;for(-1!==n&&(s-1>n?(i[n]=i[s-1],i.length=s-1,this.persistent&&(this.resultdata[n]=this.resultdata[s-1],this.resultdata.length=s-1)):(i.length=s-1,this.persistent&&(this.resultdata.length=s-1))),s=i.length,e=0;s>e;e++)i[e]>t&&i[e]--},h.prototype.mapReduce=function(t,e){try{return e(this.data().map(t))}catch(i){throw i}},c.prototype=new r,c.prototype.ensureIndex=function(i,n){if("undefined"==typeof n&&(n=!1),null===i||void 0===i)throw"Attempting to set index without an associated property";if(!this.binaryIndices.hasOwnProperty(i)||n||this.binaryIndices[i].dirty){this.binaryIndices[i]={name:i,dirty:!0,values:[]};var s,r=this.data.length,o=0;for(s=this.binaryIndices[i],o;r>o;o+=1)s.values.push(o);var a=function(i,n){return function(s,r){var o=n.data[s],a=n.data[r];return o[i]===a[i]?0:e(o[i],a[i])?1:t(o[i],a[i])?-1:void 0}}(i,this);s.values.sort(a),s.dirty=!1,this.dirty=!0}},c.prototype.ensureAllIndexes=function(t){for(var e=Object.keys(this.binaryIndices),i=e.length;i--;)this.ensureIndex(e[i],t)},c.prototype.flagBinaryIndexesDirty=function(){for(var t=Object.keys(this.binaryIndices),e=t.length;e--;)this.binaryIndices[t[e]].dirty=!0},c.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)},c.prototype.ensureIdAsync=function(t){this.async(function(){this.ensureId()},t)},c.prototype.addDynamicView=function(t,e){var i=new h(this,t,e);return this.DynamicViews.push(i),i},c.prototype.removeDynamicView=function(t){for(var e=0;e<this.DynamicViews.length;e++)this.DynamicViews[e].name===t&&this.DynamicViews.splice(e,1)},c.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},c.prototype.findAndUpdate=function(t,e){var i,n=this.where(t),s=0;try{for(s;s<n.length;s++)i=e(n[s]),this.update(i)}catch(r){this.rollback(),console.error(r.message)}},c.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 n=new Error("Object cannot be null");throw this.emit("error",n),n}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},c.prototype.clear=function(){this.data=[],this.idIndex=[],this.binaryIndices={},this.cachedIndex=null,this.cachedData=null,this.maxId=0,this.DynamicViews=[],this.dirty=!0},c.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 n,s,r=this.get(t.$loki,!0);if(!r)throw new Error("Trying to update a document not in collection.");n=r[0],s=r[1],this.data[s]=t;for(var o=0;o<this.DynamicViews.length;o++)this.DynamicViews[o].evaluateDocument(s);this.idIndex[s]=n.$loki,this.commit(),this.dirty=!0,this.emit("update",t)}catch(a){throw this.rollback(),console.error(a.message),this.emit("error",a),a}}},c.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(n){this.rollback(),console.error(n.message)}},c.prototype.removeWhere=function(t){var e;e="function"==typeof t?this.data.filter(t):new l(this,t);for(var i=e.length;i--;)this.remove(e[i])},c.prototype.removeDataOnly=function(){this.removeWhere(function(){return!0})},c.prototype.remove=function(t){if("number"==typeof t&&(t=this.get(t)),"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 n=this.get(t.$loki,!0),s=n[1],r=0;r<this.DynamicViews.length;r++)this.DynamicViews[r].removeDocument(s);this.data.splice(s,1),this.idIndex.splice(s,1),this.commit(),this.dirty=!0,this.emit("delete")}catch(o){this.rollback(),console.error(o.message),this.emit("error",o)}}},c.prototype.get=function(t,e){var i=e||!1,n=this.idIndex,s=n.length-1,r=0,o=Math.floor(r+(s-r)/2);if(t="number"==typeof t?t:parseInt(t,10),isNaN(t))throw"Passed id is not an integer";for(;n[r]<n[s];)o=Math.floor((r+s)/2),n[o]<t?r=o+1:s=o;return s===r&&n[r]===t?i?[this.data[r],r]:this.data[r]:null},c.prototype.findOne=function(t){var e=new l(this,t,null,!0);return Array.isArray(e)&&0===e.length?null:e},c.prototype.chain=function(){return new l(this,null,null)},c.prototype.find=function(t){return"undefined"==typeof t&&(t="getAll"),new l(this,t,null)},c.prototype.findOneUnindexed=function(t,e){for(var i,n=this.data.length;n--;)if(this.data[n][t]===e)return i=this.data[n];return null},c.prototype.startTransaction=function(){if(this.transactional){this.cachedData=n(this.data,"parse-stringify"),this.cachedIndex=this.idIndex,this.cachedBinaryIndex=this.binaryIndices;for(var t=0;t<this.DynamicViews.length;t++)this.DynamicViews[t].startTransaction()}},c.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()}},c.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()}},c.prototype.async=function(t,e){setTimeout(function(){if("function"!=typeof t)throw"Argument passed for async execution is not a function";t(),e()},0)},c.prototype.where=function(t){return new l(this,null,t)},c.prototype.mapReduce=function(t,e){try{return e(this.data.map(t))}catch(i){throw i}},c.prototype.no_op=function(){},f.prototype={keys:[],values:[],sort:function(t,e){return e>t?-1:t>e?1:0},setSort:function(t){this.bs=d(t)},bs:function(){return d(this.sort)},set:function(t,e){var i=this.bs(this.keys,t);i.found?this.values[i.index]=e:(this.keys.splice(i.index,0,t),this.values.splice(i.index,0,e))},get:function(t){return this.values[u(this.keys,t,this.sort).index]}},a.Collection=c,a.KeyValueStore=f,a}()});
{
"name": "lokijs",
"version": "1.1.15",
"version": "1.2.0",
"description": "Fast document oriented javascript in-memory database",

@@ -35,7 +35,3 @@ "homepage": "http://lokijs.org",

},
"dependencies": {
"gordian": "0.0.9",
"istanbul": "^0.3.2",
"mocha": "^2.0.1"
},
"dependencies": {},
"devDependencies": {

@@ -42,0 +38,0 @@ "gordian": "0.0.9",

@@ -32,2 +32,7 @@ var loki = require('../src/lokijs.js'),

var dv = users.addDynamicView('testview');
dv.applyWhere(function (obj) {
return obj.name.length > 3;
});
users.removeWhere(function (obj) {

@@ -45,2 +50,5 @@ return obj.age > 35;

suite.assertEqual('Users length after remove(int)', users.data.length, 1);
users.removeDataOnly();
suite.assertEqual('No users left after removeDataOnly()', users.data.length, 0);
suite.assertEqual('DynamicView still in existence after removing data', !!users.getDynamicView('testview'), true);
suite.report();

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc