1
1

Measure.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. interface Measurement {
  2. getText : () => string;
  3. }
  4. /**
  5. * A measure is ALWAYS created in Centimeters.
  6. * How a measure gets displayed can get changed later, so always use this class for measures!
  7. * If you're american, use the helper static functions fromInches, fromFeet to get centimeters.
  8. * For instance, 5'10" would get created as:
  9. * new Measure(Measure.fromFeet(5) + Measure.fromInches(10)
  10. *
  11. * If multiple measurements are added, it's treated as area of something simple like rectangles or cubes or whatever, they're just multiplied.
  12. */
  13. class Measure implements Measurement {
  14. private units : number;
  15. private sides : number;
  16. public constructor (...sides : Array<number>) {
  17. this.units = 1;
  18. sides.forEach((side) => {
  19. this.units *= side;
  20. });
  21. this.sides = sides.length;
  22. }
  23. // ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  24. private superscript = ["" , "" , "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"];
  25. public getText () {
  26. let meters = Math.pow(this.sides, 100);
  27. if (this.units > meters) {
  28. return (+(this.units / meters).toFixed(2)).toString() + "m" + this.superscript[this.sides];
  29. } else {
  30. return this.units.toString() + "cm" + this.superscript[this.sides];
  31. }
  32. }
  33. public getNumber () {
  34. return this.units;
  35. }
  36. public getSides () {
  37. return this.sides;
  38. }
  39. public static fromInches (inches : number) {
  40. return inches * 2.54;
  41. }
  42. public static fromFeet (feet : number) {
  43. return feet * 30.48;
  44. }
  45. }
  46. class MeasureLiquid implements Measurement {
  47. private units : number;
  48. public constructor (milliliters : number) {
  49. this.units = milliliters;
  50. }
  51. public getText () {
  52. if (this.units > 1000) {
  53. return (+(this.units / 1000).toFixed(2)).toString() + "L";
  54. } else {
  55. return this.units.toString() + "mL";
  56. }
  57. }
  58. public static fromLiters (liters : number) {
  59. return liters * 1000;
  60. }
  61. }