Search code examples
javascriptes6-map

Iterating through specified range within js es6 map


I have a sorted JavaScript map structure storing object states based on time.
Map(key:time(inMilli), value: {object attributes})

What I am needing to accomplish is to be able to check map against a start and end time to get a collection of all values between without iterating over the entirety of the map.

//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;
}

Solution

  • Ended up using jstreemap and using a TreeMap and itterating over their upper and lower bounds functions. This was really easy and would recommend.

    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();
    }