Posted By

jatkins on 10/20/15


Tagged

class math classes Maths equation Geometry straightline


Versions (?)

StraightLine class


 / Published in: JavaScript
 

Released into the public domain by Josh Atkins, 2015.

  1. sniktaDraw.classes.StraightLine = function(point1, point2) {
  2. var orthogonalToAnAxis = true;
  3.  
  4. if(arguments.length === 2) { // point1 and point2 were specified
  5. this._gradient = (point1.y - point2.y) / (point1.x - point2.x);
  6. this._yIntercept = point1.y - this.gradient * point1.x;
  7.  
  8. this._point1 = {x: point1.x, y: point1.y};
  9. this._point2 = {x: point2.x, y: point2.y};
  10. }
  11. else if(arguments.length === 1 && 'gradient' in arguments[0] && 'yIntercept' in arguments[0]) {
  12. this._gradient = arguments[0].gradient;
  13. this._yIntercept = arguments[0].yIntercept;
  14. }
  15.  
  16. if(Math.abs(this.gradient) === Infinity) {
  17. this._x = arguments.length === 2 ? point1.x : arguments[0].x;
  18. }
  19. else if(this.gradient === 0) {
  20. this._y = arguments.length === 2 ? point1.y : arguments[0].y;
  21. }
  22. else {
  23. orthogonalToAnAxis = false;
  24. }
  25.  
  26. this._orthogonalToAnAxis = orthogonalToAnAxis;
  27. };
  28. Object.defineProperties(sniktaDraw.classes.StraightLine.prototype, {
  29. x: { get: function() { return this._x; } },
  30. y: { get: function() { return this._y; } },
  31. gradient: { get: function() { return this._gradient; } },
  32. yIntercept: { get: function() { return this._yIntercept; } },
  33. orthogonalToAnAxis: { get: function() { return this._orthogonalToAnAxis; } },
  34. point1: { get: function() { return this._point1 ? {x: this._point1.x, y: this._point1.y} : null; } },
  35. point2: { get: function() { return this._point2 ? {x: this._point2.x, y: this._point2.y} : null; } }
  36. });
  37. sniktaDraw.classes.StraightLine.prototype.toString = function() {
  38. var parts,
  39. partsJoined;
  40.  
  41. if(Math.abs(this.gradient) === Infinity) {
  42. return 'x = ' + (this.point1 && this.point1.x ? this.point1.x : this.x);
  43. }
  44. else {
  45. parts = [];
  46.  
  47. if(this.gradient !== 0) {
  48. parts.push(this.gradient + 'x');
  49. }
  50.  
  51.  
  52. if(this.yIntercept !== 0) {
  53. parts.push(this.yIntercept);
  54. }
  55.  
  56. partsJoined = parts.join(' + ');
  57.  
  58. return 'y = ' + (partsJoined.length ? partsJoined : '0');
  59. }
  60. };

Report this snippet  

You need to login to post a comment.