import FDBKeyRange from"../FDBKeyRange.js";import{getByKey,getByKeyRange,getIndexByKey,getIndexByKeyGTE,getIndexByKeyRange}from"./binarySearch.js";import cmp from"./cmp.js";class RecordStore{records=[];get(key){return key instanceof FDBKeyRange?getByKeyRange(this.records,key):getByKey(this.records,key)}add(newRecord){let i;if(0===this.records.length)i=0;else if(i=getIndexByKeyGTE(this.records,newRecord.key),-1===i)i=this.records.length;else for(;i<this.records.length&&0===cmp(this.records[i].key,newRecord.key)&&-1===cmp(this.records[i].value,newRecord.value);)i+=1;this.records.splice(i,0,newRecord)}delete(key){const deletedRecords=[],isRange=key instanceof FDBKeyRange;for(;;){const idx=isRange?getIndexByKeyRange(this.records,key):getIndexByKey(this.records,key);if(-1===idx)break;deletedRecords.push(this.records[idx]),this.records.splice(idx,1)}return deletedRecords}deleteByValue(key){const range=key instanceof FDBKeyRange?key:FDBKeyRange.only(key),deletedRecords=[];return this.records=this.records.filter((record=>{const shouldDelete=range.includes(record.value);return shouldDelete&&deletedRecords.push(record),!shouldDelete})),deletedRecords}clear(){const deletedRecords=this.records.slice();return this.records=[],deletedRecords}values(range,direction="next"){return{[Symbol.iterator]:()=>{let i;if("next"===direction){if(i=0,void 0!==range&&void 0!==range.lower)for(;void 0!==this.records[i];){const cmpResult=cmp(this.records[i].key,range.lower);if(1===cmpResult||0===cmpResult&&!range.lowerOpen)break;i+=1}}else if(i=this.records.length-1,void 0!==range&&void 0!==range.upper)for(;void 0!==this.records[i];){const cmpResult=cmp(this.records[i].key,range.upper);if(-1===cmpResult||0===cmpResult&&!range.upperOpen)break;i-=1}return{next:()=>{let done,value;if("next"===direction){if(value=this.records[i],done=i>=this.records.length,i+=1,!done&&void 0!==range&&void 0!==range.upper){const cmpResult=cmp(value.key,range.upper);done=1===cmpResult||0===cmpResult&&range.upperOpen,done&&(value=void 0)}}else if(value=this.records[i],done=i<0,i-=1,!done&&void 0!==range&&void 0!==range.lower){const cmpResult=cmp(value.key,range.lower);done=-1===cmpResult||0===cmpResult&&range.lowerOpen,done&&(value=void 0)}return{done:done,value:value}}}}}}}export default RecordStore;