Caluclate overlap

Benchmark created on


Description

Two different methods of calculating overlap between two items

Setup

const s = [
  {
    c: {x:1183.5,y:438.6875,width:149.890625,height:36,top:438.6875,right:1333.390625,bottom:474.6875,left:1183.5},
    p: {x:52.5,y:438.6875,width:1156,height:36,top:438.6875,right:1208.5,bottom:474.6875,left:52.5}
  },
  {
    c: {x:-40.671875,y:438.6875,width:177.65625,height:36,top:438.6875,right:136.984375,bottom:474.6875,left:-40.671875},
    p: {x:52.5,y:438.6875,width:1156,height:36,top:438.6875,right:1208.5,bottom:474.6875,left:52.5}
  },
  {
    c: {x:627.546875,y:438.6875,width:162.59375,height:36,top:438.6875,right:790.140625,bottom:474.6875,left:627.546875},
    p: {x:52.5,y:438.6875,width:1156,height:36,top:438.6875,right:1208.5,bottom:474.6875,left:52.5}
  },
  {
    c: {x:2318.453125,y:438.6875,width:100.03125,height:36,top:438.6875,right:2418.484375,bottom:474.6875,left:2318.453125},
    p: {x:52.5,y:438.6875,width:1156,height:36,top:438.6875,right:1208.5,bottom:474.6875,left:52.5}
  }
];

Test runner

Ready to run.

Testing in
TestOps/sec
Conditions
s.forEach(({c,p}) => {
  var visibility = 0;

  if (
    c.x >= p.x
    && c.right <= p.right
  ) {
    visibility = 1;
  } else if (
    c.x < p.x && c.right > p.x
  ) {
    visibility = (c.right - p.x) / c.width;
  } else if (
    c.right > p.right && c.x < p.right
  ) {
    visibility = (p.right - c.x) / c.width;
  }
});
ready
Pure maths
s.forEach(({c,p}) => {
  var visibility = Math.min(Math.max((Math.min(p.right, c.right) - Math.max(p.x, c.x)) / c.width, 0), 1);
});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.