0

我有一个排序的 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;
}
4

2 回答 2

0
function getRange(start, stop){

    let foundValues = [];

    if (start >== stop) return [start];

    for(let [key, value] of map.entries()){
        if (key > start && key < stop) {
            foundValues.push(key);
        } else {
            return foundValues;
        }
    }  
    return foundValues;
}

一旦地图中的条目时间超出指定范围(开始和停止),您只需返回数组,这将停止迭代。

function getRange(start, stop) {

  const currentArray = Array.from(map);

  let foundValues = [];
  let currentMap = currentArray.shift();

  while (currentMap[0] > start && currentMap[0] < stop && currentArray.length) {
    foundValues.push(currentMap[1]);
    currentMap = currentArray.shift();
  }

  return foundValues;

}

使用 while 循环,这不会迭代地图中的所有项目。这仅在地图已经排序时才有效。

于 2018-09-13T18:43:09.613 回答
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();
}
于 2018-09-13T19:48:16.237 回答