Javascript - Array checking for overlapping numeric ranges

I am currently working with an array of time ranges that have both start and end values.

var timeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}]

My task requires me to determine if the selected range overlaps with any of the given time ranges. Additionally, the selected range must fall within the intervals defined by the timeRanges. For example, 140-180 and 220-250 would be valid selections.

var selected = {
    start: 150,
    end: 170
}

Answer №1

When discussing time intervals, we say that interval B 'overlaps' with interval A if:

  • B begins after A starts, but before A ends.
  • B begins before A starts, and ends after A begins.

You can create a function that determines if two time intervals overlap.

function checkOverlap(A, B) {
    if(B.start < A.start) {
        return B.finish > A.start;
    }
    else {
        return B.start < A.finish;
    }
}

Answer №2

 let isOverlapping = timeRanges.some( interval => 
  (interval.begin < selected.begin && interval.finish > selected.begin) || 
  (interval.begin < selected.end && interval.finish > selected.end) || 
  (interval.begin > selected.begin && interval.finish < selected.end)
 );

Answer №3

This code snippet provides a solution for checking the validity of a selected time range within a set of predefined time ranges. It works assuming that the time ranges are sorted; otherwise, time range sorting implementation is necessary.

function checkTimeRangeValidity(existingTimeRanges, selectedRange) {
var isRangeValid = true;
var minStartTime = existingTimeRanges[0].start;
var maxEndTime = existingTimeRanges[existingTimeRanges.length - 1].end;

if(selectedRange.start < selectedRange.end && selectedRange.start > minStartTime && selectedRange.end < maxEndTime) {
    for(var index=0; index<existingTimeRanges.length; index++) {
        if((selectedRange.start >= existingTimeRanges[index].start && selectedRange.start <= existingTimeRanges[index].end)
        || (selectedRange.end >= existingTimeRanges[index].start && selectedRange.end <= existingTimeRanges[index].end)) {
            isRangeValid = false;
            break;
        }
        else if(index != existingTimeRanges.length - 1) {
            if(selectedRange.start > existingTimeRanges[index].end && selectedRange.start < existingTimeRanges[index+1].start) {
                if(selectedRange.end < existingTimeRanges[index+1].start) {
                    break;
                }
                else {
                    isRangeValid = false;
                    break;
                }
            }
        }
    }
}
else {
    isRangeValid = false;
}
return isRangeValid;
}

var existingTimeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}];

var selectedTimeRange = {
    start: 141,
    end: 222
};

alert(checkTimeRangeValidity(existingTimeRanges, selectedTimeRange));

Answer №4

Have you thought about iterating over your selection using the array and figuring out the necessary calculations?

timeRanges.forEach(function(item, position)) {

   if (selected.start > item.start && selected.end < item.end)
      console.log('Your selection fits within element ' + position):


}

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

Converting primary key strings to BSON for the _id field in MongoDB using Mongoskin

The primary key in Mongodb is typically _id and its data type is bson. For example: {_id : "4e7020cb7cac81af7136236b"} I am interested in setting another field's value as the primary key. For instance: apple How can I convert the string "apple" to ...

Can the grunt command be executed automatically after saving code in TypeScript?

As a newcomer to FrontEnd and JavaScript coding in TypeScript, I find myself constantly needing to follow these steps after making a code change: save the code -> compile it using Grunt -> reload the webpage. It can be quite time-consuming. Is there ...

Divide a string into separate numbers using JavaScript

This snippet of code is designed to search the table #operations for all instances of <td> elements with the dynamic class ".fuel "+ACID: let k = 0; let ac_fuel = 0; parsed.data.forEach(arrayWithinData => { let ACID = parsed.data[k][0]; ...

Tips on implementing CSS to the subpar class in Vuejs

I am working on an HTML file that operates with button in Vue.js. The v-bind:class can be utilized for a single tag as shown below. It disappears based on the boolean value of bool data. <h3 v-bind:class="{active: bool}">{{counter.document}}&l ...

What causes variations in running identical code between the Node environment and the Chrome console?

let myName = "World"; function functionA() { let myName = "FunctionA"; return function() { console.log(this.myName); } } functionA()(); Executing the code above in my terminal with node results in undefined, while running it in Chrom ...

Loading gltf files with Three.js does not automatically update external variables

When I import a gltf object, it seems to render in the browser but I am unable to access it using an outside variable. What could be causing this issue? let loadedModel; gltfLoader.load('./assets/javaLogo.gltf', function(gltf){ loadedModel = ...

Encountering a frustrating internal server error 500 when attempting to insert values from JavaScript into SQL Server within Visual Studio

Here is a JavaScript code that calls a C# webmethod: var _data = { '_mStart': document.getElementById("St_Period").value, '_mEnd': document.getElementById("En_Period").value }; $.ajax({ type: "POST", url: "maps.aspx/my ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

Method not found in Angular

I am currently working on an Angular application with a C# backend that exposes services. I am trying to use AngularJS resources to access these services. However, when I call the resource in the controller, I am encountering the following error: TypeErro ...

A step-by-step guide on leveraging ethereumjs-tx within a web browser

Is it necessary to install npm ethereumjs-tx when utilizing the browser-based version downloaded directly from GitHub? If so, how can we incorporate the ethereumjs-tx module into our script file? It seems like these are two separate components based on ...

I am currently working on determining whether a given string is a palindrome or not

I'm currently working on a function that checks whether a given string is a palindrome. So far, my tests are passing except for the following cases: (_eye, almostomla, My age is 0, 0 si ega ym.) This is the function I've implemented: function pa ...

Executing jQuery callback functions before the completion of animations

My issue revolves around attempting to clear a div after sliding it up, only to have it empty before completing the slide. The content I want to remove is retrieved through an Ajax call. Below you will find my complete code snippet: $('.more& ...

Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition: function myFunc( id: string, optionalParamOne?: number, optionalParamTwo?: string ) { console.log(optionalParamTwo); } If I want to call this function and only provide the id and optionalParamTwo, without need ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...

Creating and sending an email using a contact form in Create-React-App

Currently, I am in the process of developing a website using create-react-app from GitHub. My next task is to create a contact page where user information will be submitted and sent to a designated email address. However, my lack of experience with back-e ...

Convert price to Indonesian Rupiah currency format with the help of Vue.js

Can someone help me convert the price format from IDR 50,000.00 to IDR 50.000 using JavaScript and Vue? I found a script on this website, but I am having trouble understanding how it works. The script looks like this: replace(/(\d)(?=(\d{3})+(?: ...

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

Is there a way to adjust the font size in Javascript/Html without changing the color?

I have a code snippet that creates a button to increment a variable, and I want to change the font size of the displayed variable. This code is for a game akin to cookie clicker. <div class="game-object"> <script type="text/javascript>"; var c ...

Limit the execution speed of a JavaScript function

My JavaScript code is set up to trigger a click event when the user scrolls past a specific element with the class .closemenu. This is meant to open and close a header menu automatically as the user scrolls through the page. The problem I'm facing is ...

"Learn how to seamlessly submit a form without reloading the page and send data back to the same page using Node and Express

I've already reviewed a few questions on this platform. They all focus on submitting post requests, but I believe the process should be similar for get requests as well. Therefore, I made modifications to my code to accommodate get requests. However, ...