Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Feb 22nd, 2012  |  syntax: None  |  size: 1.75 KB  |  views: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. function Segment(x, y)
  2. {
  3.   if (x < y) {
  4.     this.x = x;
  5.     this.y = y;
  6.   } else {
  7.     this.x = y;
  8.     this.y = x;
  9.   }
  10. }
  11.  
  12. Segment.prototype.length = function ()
  13. {
  14.   return (this.y - this.x);
  15. }
  16.  
  17. Segment.prototype.before = function (s)
  18. {
  19.   return (this.x < s.x);
  20. }
  21.  
  22. // Returns the intersection of segments s1 and s2
  23. // or null is it doesn't exist
  24. Segment.intersection = function (s1, s2)
  25. {
  26.   if (s2.before(s1)) {
  27.     tmp = s1;
  28.     s1 = s2;
  29.     s2 = tmp;
  30.   }
  31.   if (s1.y < s2.x) {
  32.     // No intersection
  33.     return null;
  34.   } else {
  35.     return new Segment(s2.x, Math.min(s1.y, s2.y));
  36.   }
  37. }
  38.  
  39. function Point(x, y)
  40. {
  41.   this.x = x;
  42.   this.y = y;
  43. }
  44.  
  45. // A rectangle is defined by its left corner p0,
  46. // its length dx and high dy
  47. function Rectangle(p0, dx, dy)
  48. {
  49.   this.p0 = p0;
  50.   this.dx = dx;
  51.   this.dy = dy;
  52. }
  53.  
  54. Rectangle.prototype.lowerEdge = function ()
  55. {
  56.   return new Segment(this.p0.x, this.p0.x + this.dx);
  57. }
  58.  
  59. Rectangle.prototype.leftEdge = function ()
  60. {
  61.   return new Segment(this.p0.y, this.p0.y + this.dy);
  62. }
  63.  
  64. // s1 should be the lower edge and s2 the left one.
  65. // And they *must* shape a rectangle
  66. Rectangle.fromSegments = function (s1, s2)
  67. {
  68.   return new Rectangle(new Point(s1.x, s2.x), s1.length(), s2.length());
  69. }
  70.  
  71. // Return the intersection of r1 and r2
  72. // or null is it doesn't exist
  73. Rectangle.intersection = function (r1, r2)
  74. {
  75.   var sleft = Segment.intersection(r1.leftEdge(), r2.leftEdge());
  76.   var slower = Segment.intersection(r1.lowerEdge(), r2.lowerEdge());
  77.   if (sleft == null || slower == null) {
  78.     return new Rectangle(new Point(0,0), 0, 0);
  79.   } else {
  80.     return Rectangle.fromSegments(slower, sleft);
  81.   }
  82. }
  83.  
  84. Rectangle.prototype.area = function ()
  85. {
  86.   return this.dx * this.dy;
  87. }