What is the best way to divide two ranges that are intersecting?

Seeking a method to divide two overlapping ranges when they intersect.

This is my current progress using typescript,

type Range = {
  start: number;
  end: number;
};
function splitOverlap(a: Range, b: Range): Range[][] {
  let result = [];
  const intersect = {
    start: Math.max(a.start, b.start),
    end: Math.min(a.end, b.end),
  };

  let a1: Range;
  let a2: Range;

  if (a.start >= intersect.start) {
    a1 = {
      start: a.start,
      end: Math.min(a.end, intersect.end),
    };

    a2 = {
      start: Math.max(a.start, intersect.start),
      end: Math.min(a.end, intersect.end),
    };
  } else if (a.start < intersect.start) {
    a1 = {
      start: a.start,
      end: Math.min(a.end, intersect.end),
    };

    a2 = {
      start: intersect.start,
      end: Math.min(a.end),
    };
  }

  return [
    [a1, a2],
    [b, b],
  ];
}

/* 
    Input
    A  |-------------|
    B         |-------------|

    Output
    A |-------|------|
    B         |------|------|

    Input
    A  |-------------|
    B     |-------|

    Output
    A  |--|-------|--|
    B     |-------|

*/

I am not tasked with merging, only splitting when overlap occurs.

My split function first determines the intersection between the ranges, then attempts to split the input ranges utilizing this intersect data. I'm unsure of the most effective approach.

Answer №1

Your request for handling two possibilities will be met with this JavaScript code

function split(a, b) {

    const start_first = a.start < b.start ? a : b;
    const end_last = a.end > b.end ? a : b;
  // Second possibility
  if(JSON.stringify(start_first) === JSON.stringify(end_last)) {
    const split1 = [{start: start_first.start , end: b.start},
    {start: b.start , end: b.end},{start: b.end , end: a.end}
    ]
    const split2 = [{start: b.start , end: b.end},]
    return [split1, split2]
  } else {
  // First possibility
    const split1 = [{start: start_first.start , end: b.start},
  {start: b.start , end: start_first.end}]
  const split2 = [{start: b.start , end: start_first.end},
  {start: start_first.end , end: b.end}]
  return [split1, split2]
  }
}
console.log("Handling first possibility - Input: {start: 10, end: 20},{start: 15, end: 25} ::", split({start: 10, end: 20},{start: 15, end: 25}))
console.log("Handling second possibility - Input: {start: 10, end: 30},{start: 15, end: 25}", split({start: 10, end: 30},{start: 15, end: 25}))

Answer №2

After much effort, I have achieved this

function splitOverlap(a: Range, b: Range): [Range[], Range[]] {
        const intersect: Range = {
            start: Math.max(a.start, b.start),
            end: Math.min(a.end, b.end),
        };

        const createNewRanges = (range: Range, intersect: Range): Range[] => {
            const ranges = [...Object.values(getRange(range)), ...Object.values(intersect)];
            const uniqueRanges = uniq(ranges.sort());
            const updatedRanges = [];

            for (let i = 1; i < uniqueRanges.length; i++) {
                const current = uniqueRanges[i];
                const previous = uniqueRanges[i - 1];

                updatedRanges.push({
                    ...range,
                    start: previous,
                    end: current,
                });
            }

            return updatedRanges;
        };

        const getRangeValues = <T = any>({ start, end }: Range & T): Range => {
            return {
                start,
                end,
            };
        };

        const setSplit1 = createNewRanges(a, intersect);
        const setSplit2 = createNewRanges(b, intersect);

        return [setSplit1, setSplit2];
    }

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

What is hindering me from fetching the information stored in my json file?

Currently, I am delving into learning AngularJS by working on a simple webpage for a company. This page will showcase products that are fetched from a json file. Following a tutorial from the AngularJS website, which covers the exact task I aim to achieve, ...

What is the best way to modify the Xtype attribute based on whether the device is running on Android or iOS

I am currently working on a project using Extjs6.0.2, but I have encountered an issue with creating the xtype: 'namefield'. It seems that this type of xtype is supported on Android devices but not on iOS devices. Despite this challenge, I am dete ...

What's the best way to trigger an alert popup after calling another function?

Here are some HTML codes I've been working with: <button id="hide" onclick="hide()">Hide</button> <p id="pb">This paragraph has minimal content.</p> My goal is to have the paragraph hide first when the button is clicked, foll ...

The 'fs' module does not seem to have an immediate impact; a server restart may be necessary for the changes to take

This NodeJS project involves starting the server with npm start. The project reads files from a folder called "./mydir/" using 'fs.readdirSync'. It then pushes these files into an array and prints them on the console. var fs = require('fs ...

Access any nested node within a JSON/JS object by specifying the key's value

After spending hours searching on various forums for a solution to my problem, I have yet to find one that directly addresses the issue I am facing. So, please take a moment to review the details below. The object structure in question is as follows: let ...

Is there a way to retrieve a compilation of custom directives that have been implemented on the Vue 3 component?

Is there a way to retrieve the list of custom directives applied to a component? When using the getCurrentInstance method, the directives property is null for the current component. I was expecting to see 'highlight' listed. How can I access the ...

Typescript is being lenient with incorrect use of generics, contrary to my expectations of error being thrown

Encountered a puzzling Typescript behavior that has left me confused. Take a look at the following code snippet: interface ComponentProps<T> { oldObject: T } function Component<T>({ oldObject }: ComponentProps<T>) { const newObject = ...

Upgrading from Angular v6 to v8: Troubleshooting the issue of "The loader "datatable.component.css" did not return a string error"

I am currently in the process of updating my Angular project from version 6 to version 8. However, I encountered an error message in the console: ERROR: The loader "foo/node_modules/@swimlane/ngx-datatable/release/components/datatable.component.css" di ...

Having trouble importing the "@angular/material" module

I'm completely new to working with the MEAN stack and currently running into issues with Angular's material module. I am attempting to bring in the "@angular/material" module into my code, but encountering an error each time I try to import it. T ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

How can I retrieve information from a topic using kafka-node?

Having trouble reading data from a Kafka server? You may encounter an error message stating that the topic does not exist. Here are some questions to guide you: 1- How can I ensure that my Kafka connection is established? 2- What is the process for retri ...

Building a remote shell using Node.js with the ability to interpret control sequences

Currently, I am working on developing a remote shell using Node.js. Here's the code that I have implemented so far : Client var net = require('net'); var client = net.connect({port: 1234}, function(){ process.stdin.pipe(client); clien ...

Encountering JSON error when invoking multiple functions

Encountering JSON Error when calling multiple functions Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0 I've been attempting to call multiple functions in jQuery but keep getting an error. I've tried various soluti ...

Is it possible to combine Ajax, JS, HTML, PHP, and MySQL in a single project?

I am looking to create a web application and wondering if I can integrate Ajax, JavaScript, HTML, PHP, and MySQL all together? ...

Exploring the realm of unit testing in the NestJS CQRS architecture journey

We're currently working on writing unit tests using Jest for our application and are facing difficulties in testing sagas. Specifically, we're having trouble testing the saga itself. During our unit testing process, we've encountered an iss ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

What is the process for defining the root of a project in ESLint?

I've been working on a project using Next.js and Typescript. My imports look like this: import Component from "/components/Component/Component";, with the root directory being specified as /src. This setup works fine in Next.js, but ESLint k ...

Loop through an HTML table in order to emphasize variations in cells that contain multiple comparison items

I am interested in highlighting variances between the initial row of a table and all other rows based on columns. I have successfully managed to achieve this when each cell contains only one item/comparison. However, I would like to expand this to include ...

Discrepancy in functionality between Android and JavaScript Parse API

Using the open source version of Parse Server as a back end, my Android application saves objects to the server's DB in the form of key-value pairs encoded as JSON. However, when trying to retrieve the same object from an Ionic 2 app using the JS Pars ...

Having trouble with Axios PUT request not sending complete data to the server using JavaScript

One issue I'm encountering is that when sending an axios request with specific data, not all of the data gets updated in the user model. Here's a look at my code: Here is the Front-End code with axios request: import axios from "axios" ...