I have this simulation JavaScript coffee machine to make and I'm having problem with two methods, one of which adds water (coffee eg.) and other that empty's it. This is what I got for first method:
let coffeeMachine = {
water: 400,
coffee: 10,
milk: 100,
credit: 100,
waterStatus: function () {
document.getElementById('water-status').innerText = this.water;
},
addWater: function () {
let addWater = prompt('Unesite kolicinu vode koju zelite da dodate');
if (addWater === null || addWater.trim().length === 0) {
alert('Morate uneti koliko vode zelite');
return;
} else if (isNaN(addWater) || addWater.startsWith('-') || addWater % 1 !== 0) {
alert('Unos mora biti pozitivna brojcana vrednost');
return;
} else if (this.water < 400) {
addWater = Number(addWater);
this.water += addWater;
} else {
alert('Maksimalan unos vode je 400');
return;
}
this.waterStatus();
},
Problem with this one is that the total value can not be greater that 400, and it only works when I first enter the value that is greater than 400 (alert pops up), but if add 100, and than 500 it will write it (600), not considering the condition. Is it that I'm not creating new variable that will collect the sum of this.water and addWather, or I'm missing something else?
Second method needs to empty water and check if the current status of the water is bigger than the value we forwarder to prompt. I have this:
emptyWater: function (water) {
if (this.water > addWater) {
this.water -= addWater;
this.waterStatus(water);
document.getElementById('message').innerText = 'Pouring water';
} else {
document.getElementById('message').innerText = 'Machine is out of water \n';
}
},
In the object itself I have predefined values for water, coffee eg.
Those values I collected in water status function, but did I not made it dynamic?
waterStatus: function () {
document.getElementById('water-status').innerText = this.water;
},
Check for the new total value, so the condition will work:
....
} else if (this.water + Number(addWater) < 400) {
addWater = Number(addWater);
this.water += addWater;
...
Update
I think you should change the parameter water
to addWater
in the emptyWater
function:
emptyWater: function (addWater) {
if (this.water > addWater) {
this.water -= addWater;
this.waterStatus();
...
You can use it in the addWater
function, as:
...
} else if (this.water < 400) {
addWater = Number(addWater);
this.water += addWater;
this.emptyWater(addWater);
...
And the waterStatus
would be:
waterStatus: function () {
document.getElementById('water-status').innerText = this.water;
},