You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const US_LIQUID_GALLONS_TO_CUBIC_INCHES = 231
  2. const CUBIC_INCHES_TO_US_LIQUID_GALLONS = 1 / US_LIQUID_GALLONS_TO_CUBIC_INCHES
  3. const toLiquid = cubicInches => cubicInches * CUBIC_INCHES_TO_US_LIQUID_GALLONS
  4. const fromLiquid = gallons => gallons * US_LIQUID_GALLONS_TO_CUBIC_INCHES
  5. class Container {
  6. constructor({ l, w, h }, level = 0) {
  7. this.l = l
  8. this.w = w
  9. this.h = h
  10. this.level = level
  11. }
  12. get liquidVolumeCapacity() {
  13. return toLiquid(this.l * this.w * this.h)
  14. }
  15. get liquidVolumeFilled() {
  16. return toLiquid(this.l * this.w * this.level)
  17. }
  18. get liquidVolumeRemaining() {
  19. return this.liquidVolumeCapacity - this.liquidVolumeFilled
  20. }
  21. }
  22. /** Functional Core */
  23. const _changeLevel = (amount, container) => {
  24. const alteredLevel =
  25. fromLiquid(container.liquidVolumeFilled + amount) /
  26. container.l /
  27. container.w
  28. return createContainer(container, alteredLevel)
  29. }
  30. const createContainer = ({ l, w, h }, level) => {
  31. if (Math.sign(l) + Math.sign(w) + Math.sign(h) !== 3)
  32. return console.error(
  33. `[Error] All dimensions must be positive and greater than zero!`
  34. )
  35. return new Container({ l, w, h }, level)
  36. }
  37. const fill = ({ container, amount }) => _changeLevel(amount, container)
  38. const drain = ({ container, amount }) => _changeLevel(-1 * amount, container)
  39. myTank = createContainer({ l: 12, w: 12, h: 12 })
  40. console.log('capacity:', myTank.liquidVolumeCapacity)
  41. console.log('filled:', myTank.liquidVolumeFilled)
  42. myTank = fill({ amount: myTank.liquidVolumeCapacity, container: myTank })
  43. console.log('\nremaining liquid volume:', myTank.liquidVolumeRemaining)
  44. console.log('remain h:', myTank.h - myTank.level)
  45. myTank = drain({ amount: 4, container: myTank })
  46. console.log('\nremaining liquid volume:', myTank.liquidVolumeRemaining)
  47. console.log('remain h:', myTank.h - myTank.level)
  48. console.log('filled:', myTank.liquidVolumeFilled)
  49. myTank = fill({ amount: 3, container: myTank })
  50. console.log('\nremaining liquid volume:', myTank.liquidVolumeRemaining)
  51. console.log('remain h:', myTank.h - myTank.level)
  52. console.log('filled:', myTank.liquidVolumeFilled)