Created
May 8, 2019 11:18
-
-
Save tarik02/dc12f93e779274b7f78bcdb77e76af43 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function intersect(r1, r2) { | |
if (r2.p1.x > r1.p2.x | |
|| r2.p2.x < r1.p1.x | |
|| r2.p1.y > r1.p2.y | |
|| r2.p2.y < r1.p1.y) { | |
return null; | |
} | |
return { | |
p1: { | |
x: Math.max(r1.p1.x, r2.p1.x), | |
y: Math.max(r1.p1.y, r2.p1.y), | |
}, | |
p2: { | |
x: Math.min(r1.p2.x, r2.p2.x), | |
y: Math.min(r1.p2.y, r2.p2.y), | |
}, | |
}; | |
} | |
function is_valid(r) { | |
return r && r.p1.x < r.p2.x && r.p1.y < r.p2.y; | |
} | |
function enumerate_rect(r) { | |
var results = []; | |
if (is_valid(r)) { | |
for (var x = r.p1.x; x <= r.p2.x; ++x) { | |
for (var y = r.p1.y; y <= r.p2.y; ++y) { | |
results.push({x: x, y: y}); | |
} | |
} | |
} | |
return results; | |
} | |
function enumerate_non_intersection(r, i) { | |
return [].concat( | |
enumerate_rect({ p1: { x: r.p1.x, y: r.p1.y }, p2: { x: i.p1.x - 1, y: i.p1.y - 1 } }), | |
enumerate_rect({ p1: { x: r.p1.x, y: i.p1.y }, p2: { x: i.p1.x - 1, y: i.p2.y } }), | |
enumerate_rect({ p1: { x: r.p1.x, y: i.p2.y + 1 }, p2: { x: i.p1.x - 1, y: r.p2.y } }), | |
enumerate_rect({ p1: { x: i.p1.x, y: r.p1.y }, p2: { x: i.p2.x, y: i.p1.y - 1 } }), | |
enumerate_rect({ p1: { x: i.p1.x, y: i.p2.y + 1 }, p2: { x: i.p2.x, y: r.p2.y } }), | |
enumerate_rect({ p1: { x: i.p2.x, y: r.p1.y }, p2: { x: r.p2.x, y: i.p1.y - 1 } }), | |
enumerate_rect({ p1: { x: i.p2.x, y: i.p1.y }, p2: { x: r.p2.x, y: i.p2.y } }), | |
enumerate_rect({ p1: { x: i.p2.x, y: i.p2.y + 1 }, p2: { x: r.p2.x, y: r.p2.y } }), | |
[] | |
); | |
} | |
function get_exclusives(r1, r2) { | |
var i = intersect(r1, r2); | |
if (is_valid(i)) { | |
return [ | |
enumerate_non_intersection(r1, i), | |
enumerate_non_intersection(r2, i), | |
]; | |
} else { | |
return [ | |
enumerate_rect(r1), | |
enumerate_rect(r2), | |
]; | |
} | |
} | |
console.log(get_exclusives({ | |
p1: {x: 10, y: 10}, | |
p2: {x: 20, y: 20}, | |
}, { | |
p1: {x: 15, y: 15}, | |
p2: {x: 25, y: 25}, | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment