Home > Net >  (Javascript) Check if 2 Values Overlap and give percentage value
(Javascript) Check if 2 Values Overlap and give percentage value

Time:11-05

I have the following code adapted to check if a range overlaps:

function isOverlapping(prevHighLow, currentHighLow) {

  const a = prevHighLow[0];
  const b = prevHighLow[1];
  
    const c = currentHighLow[0];
    const d = currentHighLow[1];

    if (a < d && b > c) {

      return true;
    }

  return false;
}

var prevHighLow = [12350, 12900]

var currentHighLow = [12100, 12800]

console.log(isOverlapping(prevHighLow, currentHighLow)) //returns true

It works 100%, however I would like to also return a percentage (from 0 to 100%) of how much they overlap?

Thank you!

CodePudding user response:

The only percentage that might make sense is percentage of common area vs total area. So

// function from https://www.tutorialspoint.com/get-intersection-between-two-ranges-in-javascript
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];
};

var arr1 = [0, 12];
var arr2 = [6, 14];
var intersection = findRangeIntersection(arr1, arr2)

console.log(""   intersection)


function size(arr1) {
  return arr1[1] - arr1[0];
}

var percent = size(intersection) / (size(arr1)   size(arr2)) * 100
console.log(percent, '%');

CodePudding user response:

function isOverlapping(prevHighLow, currentHighLow) {

const a = prevHighLow[0];
const b = prevHighLow[1];

for (const interval of currentHighLow) {

  const c = currentHighLow[0];
  const d = currentHighLow[1];

  if (a < d && b > c) {

    let smallerRange = 0;
    let largerRange = 0;

    if (b-a < d-c){
      smallerRange = b-a;
      largerRange = d-c;
    } else {
      smallerRange = d-c;
      largerRange = b-a;
    }
    return [true, Math.round((smallerRange/largerRange)*100)   "%"];
  }
}
  • Related