Navigating through designated interval inside js es6 map

I am currently working with a JavaScript map structure that is sorted based on time, storing object states.

Map(key:time(inMilli), value: {object attributes})

My goal is to efficiently retrieve a collection of all values within a specific start and end time range from the map without having to iterate over the entire map.

//here is my current approach. However, I would like to avoid comparing against the 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 equal to or after end time
  if(start >= stop) return [start];

  //search the map for values within the given range
  for([key,value] of map){
    if(key > start && key < stop) foundValues.push(key)
  }  
  return foundValues;
}

Answer №1

function getValuesInRange(start, stop){

    let valuesInRange = [];

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

    for(let [k, v] of myMap.entries()){
        if (k > start && k < stop) {
            valuesInRange.push(k);
        } else {
            return valuesInRange;
        }
    }  
    return valuesInRange;
}

The function above retrieves values within a specified range from a map and stops the iteration once the range is exceeded.

function findValuesWithinRange(start, stop) {

  const entriesArray = Array.from(myMap);

  let valuesInRange = [];
  let currentEntry = entriesArray.shift();

  while (currentEntry[0] > start && currentEntry[0] < stop && entriesArray.length) {
    valuesInRange.push(currentEntry[1]);
    currentEntry = entriesArray.shift();
  }

  return valuesInRange;

}

This implementation using a while loop avoids iterating through all map items and assumes the map is already sorted.

Answer №2

Utilized the jstreemap library to work with a TreeMap and iterate through their upper and lower bounds functions. This approach proved to be quite straightforward and efficient, definitely worth trying out.

let map = new TreeMap(); // Just emphasizing that this is now a TreeMap
map = dataService.getData();

function getRange(startTime, endTime){
  let from = map.lowerBound(startTime);
  let to = map.upperBound(endTime);
  let it = from; // Initialize to the first value in iterator
  let foundValues = [];

  // Iterates only from the first requested object to the last. Avoids unnecessary searches for values.
  while(!it.equals(to)){
    foundValues.push(it);
    it.next();
  }
  return foundValues;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one hand over a file to the http.write method in Node?

When I attempt to print a file using the res.write() method, I encounter an error: TypeError: First argument must be a string or Buffer This is my code snippet: var fs = require("fs"); var http = require("http"); http.createServer(function (req, res){ ...

Securing specific pages in Angular front-end: A guide to implementing authentication

Interested in developing a web application using Node.js that allows users to log in (authentication). The app will have 3 non-secure pages (/home, /contact, /about) and one secure page (/admin). I've been consulting the Mean Machine book from scotch. ...

Ways to enable file/result downloads on a website using HTML

Could you please take a look at this repository: https://github.com/imsikka/ArtGallery I am looking to create a downloadable result using a download button. I can create the button, but I am unsure of how to make the file actually downloadable. Do I need ...

Encountering an issue: "req.validatonErrors" is throwing an error as it is not recognized as a function. The

Currently, I am a beginner and enrolled in a Udemy course to learn about node/express/mongo. However, I have hit a roadblock that is causing some difficulty for me. The issue seems to be related to the usage of express-validator in my form code. I suspect ...

The carousel spun around, each section moving to the side on its own

One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on. I've attem ...

What is the best method to transfer a password securely to a server using Vue or JavaScript?

I've developed Vue components for both login and registration functionalities. Now, I'm faced with the question of how to securely send passwords to the server. Should I encrypt the password using bcrypt on the client side before sending it to La ...

Updating the Three.js Raycaster following CSS transformation

I am new to diving into the world of WebGL with Three.js. As a beginner, I wanted to experiment with something similar to this. I've managed to get most of it working, but I'm currently struggling with updating the raycaster and object after shif ...

An in-depth guide on integrating lint-staged with jest and utilizing --collectCoverageFrom

I have incorporated lint-staged along with Jest testing framework to solely test the files that have been altered since the last commit, following the instructions outlined in this blog. Here is my current configuration: "src/**/*.{ts}": [ "prettier -- ...

How can one accurately pair the key and its corresponding value from an array of objects to create a new object containing only that key?

In my JavaScript code, I am attempting to create a function that can match a specific key with an array of objects fetched from an API. This matching process is based on two parameters obtained from the API: a key (which is a string) and an array of object ...

Tips for conducting unit tests on navigator.notification.alert

I am currently facing a challenge in writing a unit test for a JavaScript function where I need to fake the navigator.notification.alert method. Can anyone provide suggestions or solutions? Below is the code snippet that I have attempted: navigator = { ...

Performing a single database call to insert multiple subdocuments at once

If I have a document containing an array of objects. Data = { _id: 1, total_amount: 0, subDataArray: [ { _id: 1, amount: 0 }, { _id: 2, amount: 1 }, ... ] } Updating the total_amount can be done simply like ...

How can Vuetify be used to create a v-row that floats above other elements, maintains a fixed position, and still adheres to the width of its parent element

Currently, I am integrating Vuetify into my project and facing an issue with making an element inside a v-row float and fixed while still maintaining the width of the parent element. Here's the code snippet I am working with: <v-container> ...

Angular 7 - Issue with rendering only the "dist" folder on the browser, not the "src" folder when using nodejs

Greetings! I'm embarking on a new project involving a nodejs app with angular7. Below is the content of my mail server.js file in nodejs: var express = require('express'); var mysql = require('mysql'); var bodyParser = require(&a ...

Three.js OBJLoader causing Cross-Origin Resource Sharing problem

I'm attempting to access an object from my system using OBJLoader, but I keep encountering a CORS error that states: Access to XMLHttpRequest at 'file:///Users/pranayankittiru/Desktop/tasks/resources/Pix.obj' from origin 'null' ha ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

Is there a restriction on the number of routes available from Google Maps Directions Service?

Utilizing the Google Maps Directions API, I am able to calculate the distance between the current user's location and various stores. Everything functions properly until I exceed 10 store locations, at which point the API ceases to operate due to its ...

Creating dynamic images with PHP GD library

I am encountering a problem where Hindi text added to an image using PHP GD is appearing as squares. It seems like PHP GD does not support rendering Hindi text properly. Is there a solution to fix this issue? Alternatively, are there any other methods to ...

Modification of window size using jQuery animations

Currently, I am working on creating a sidebar that slides in from the left side of the screen. To achieve this effect, I have set the menu element to float left with a width of 40% and a margin-left of -40%. However, when I try to reveal the sidebar by sw ...

Attempting to extract data from a JSON object within a multidimensional array

Looking at the JSON structure that I need to work with: [ { "result":"OK", "message":"Display", "value":200, "rows":29 } , [ { "personID":1, "img_path":"/1234/", "img ...

Shuffle the elements in an array while preserving the original sequence

I am trying to find a way to randomize a list of email addresses, remove any duplicates, and still maintain the original order. I have successfully achieved each task individually but struggle when combining them all together. Below is my attempt which i ...