Advertisement
TeeZ0NE

coffeMachine in func proto

Jan 21st, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * parent constructor
  3. * @param {array} arg - arguments
  4. */
  5. function Machine(...arg){
  6.   let _enabled = false;
  7.   let [_power] = arg;
  8.   this.enable = ()=>{_enabled = true};
  9.   this.disable = ()=>{_enabled=false};
  10.   Object.defineProperties(this, {
  11.     "_enabled": {
  12.       get: ()=>{return _enabled;}
  13.     },
  14.     "_power":{
  15.       get:()=>{return _power;}
  16.     }
  17.   })
  18. }
  19.  
  20. /**
  21. * CoffeeMachine constructor
  22. * @param {integer} power
  23. * @param {integer} capacity
  24. */
  25. function CoffeeMachine(power, capacity) {
  26.   Machine.apply(this,arguments);
  27.   if (!isFinite(this._power) || !isFinite(capacity)) throw new Error('Power and Capacity mast be a Integer')
  28.   let waterAmount = 0;
  29.   let timerId;
  30.   let self = this;
  31.   let machine_enable = this.enable; //assign parent enablemethod
  32.  
  33.   // rewrie own method
  34.   this.enable = ()=>{
  35.     machine_enable.call(this);//call parent method enable
  36.     this.run();
  37.   }
  38.   this.run = () => {
  39.     console.log(`Is running: ${this._enabled}`);
  40.     timerId = setTimeout(onReady, getBoilTime());
  41.   }
  42.  
  43.   this.stop = () => {
  44.     clearTimeout(timerId);
  45.     this.disabled();
  46.     console.log('Stopped!');
  47.   };
  48.   //getter/seter via method
  49.   this.wa = (amount = 0) => {
  50.     if (!amount) return waterAmount;
  51.     waterAmount = amount;
  52.   };
  53.  
  54.   this.addWater = (addWater)=>{
  55.     let newAmount = waterAmount + addWater;
  56.     if (newAmount<0 || newAmount>capacity) throw new Error("Check water add count");
  57.     else waterAmount = newAmount;
  58.   };
  59.   //getter/setter via property
  60.   Object.defineProperties(this, {
  61.     "waterAmount": {
  62.       get: () => waterAmount,
  63.       set: (amount) => {
  64.         switch (amount) {
  65.           case (amount < 0) :
  66.             throw new Error('Less then 0');
  67.             break;
  68.           case (amount > capacity) :
  69.             throw new Error('More then capacity');
  70.             break;
  71.           default:
  72.             waterAmount = amount;
  73.         }
  74.       }
  75.     }
  76.   });
  77.  
  78.   let getBoilTime = function () {
  79.     const c = 4200;
  80.     const dT = 80;
  81.     return c * waterAmount * dT / power;
  82.   }; //.bind(this);
  83.  
  84.   function onReady() {
  85.     console.log('Coffee ready!');
  86.     self.disable();
  87.   }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement