Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get intersection between two ranges in JavaScript
In JavaScript, finding the intersection between two numerical ranges involves determining the overlapping portion. A range is typically represented as an array with two elements: [start, end].
Understanding Range Intersection
The intersection of two ranges is the overlapping segment. For ranges [2, 5] and [4, 7], the intersection is [4, 5] because that's where they overlap.
const arr1 = [2, 5];
const arr2 = [4, 7];
console.log("Range 1:", arr1);
console.log("Range 2:", arr2);
Range 1: [ 2, 5 ] Range 2: [ 4, 7 ]
Algorithm
To find the intersection, we need:
- Left boundary: Maximum of both starting points
- Right boundary: Minimum of both ending points
Example
const arr1 = [2, 5];
const arr2 = [4, 7];
const findRangeIntersection = (arr1 = [], arr2 = []) => {
const [el11, el12] = arr1;
const [el21, el22] = arr2;
const leftLimit = Math.max(el11, el21);
const rightLimit = Math.min(el12, el22);
return [leftLimit, rightLimit];
};
console.log(findRangeIntersection(arr1, arr2));
[ 4, 5 ]
Handling Edge Cases
Sometimes ranges don't overlap. We should check if the intersection is valid:
const findValidIntersection = (range1, range2) => {
const [start1, end1] = range1;
const [start2, end2] = range2;
const leftLimit = Math.max(start1, start2);
const rightLimit = Math.min(end1, end2);
// Check if intersection is valid
if (leftLimit
Overlapping: [ 4, 5 ]
Non-overlapping: null
Multiple Examples
const testCases = [
[[1, 5], [3, 7]], // [3, 5]
[[0, 2], [1, 4]], // [1, 2]
[[5, 10], [2, 6]], // [5, 6]
[[1, 3], [4, 6]] // No overlap
];
testCases.forEach(([range1, range2], index) => {
const result = findValidIntersection(range1, range2);
console.log(`Test ${index + 1}: [${range1}] ? [${range2}] = ${result ? `[${result}]` : 'No intersection'}`);
});
Test 1: [1,5] ? [3,7] = [3,5]
Test 2: [0,2] ? [1,4] = [1,2]
Test 3: [5,10] ? [2,6] = [5,6]
Test 4: [1,3] ? [4,6] = No intersection
Conclusion
Finding range intersection involves taking the maximum of start values and minimum of end values. Always validate that the resulting range is valid (left ? right) to handle non-overlapping cases.
Advertisements
