我有一个排序的JavaScript映射结构,该结构根据时间存储对象状态。
Map(key:time(inMilli), value: {object attributes})
我需要完成的是能够对照开始时间和结束时间检查地图,以获取之间的所有值的集合,而无需遍历整个地图。
//currently using something like this. But would like to not compare against entire map of times
let map = dataService.getTimeData()//returns map of all objects
let updates = getRange(someTime, someTime);
function getRange(start, stop){
let foundValues = [];
//if start is end or after end time
if(start >== stop)return [start];
//search map for values
for([key,value] of map){
if(key > start && key < stop)foundValues.push(key)
}
return foundValues;
}
答案 0 :(得分:0)
最后使用jstreemap并使用TreeMap并在其上限和下限功能上进行操作。这真的很容易,建议您这样做。
let map = new TreeMap();//just wanted to show that this is a TreeMap now
map = dataService.getData();
function getRange(startTime, endTime){
let from = map.lowerBound(startTime);
let to = map.upperBound(endTime);
let it = from;//initialize to first value in iterator
let foundValues = [];
//only iterates from first object requested to last. No longer needs to search any unnecessary values.
while(!it.equals(to)){
foundValues.push(it);
it.next();
}
return foundValues();
}