80 lines
1.8 KiB
JavaScript
80 lines
1.8 KiB
JavaScript
const Product = require('./product');
|
|
|
|
module.exports = class VendingMachine {
|
|
constructor() {
|
|
this.id = Math.floor(Math.random() * 1000);
|
|
this.products = [];
|
|
}
|
|
|
|
addProduct(name, quantity, price) {
|
|
if (this.products[name]) {
|
|
this.products[name].quantity += quantity;
|
|
} else {
|
|
if (!price) {
|
|
console.error('Price not specified');
|
|
return 0;
|
|
}
|
|
this.products[name] = new Product(name, quantity, price);
|
|
}
|
|
return this.products[name];
|
|
}
|
|
|
|
buyProduct(id) {
|
|
this.products.forEach((product) => {
|
|
if (product.id == id) {
|
|
product.quantity--;
|
|
}
|
|
});
|
|
}
|
|
|
|
getProducts() {
|
|
return this.products;
|
|
}
|
|
|
|
getProductById(id) {
|
|
let product = null;
|
|
this.products.forEach((element) => {
|
|
if (element.id == id) {
|
|
product = element;
|
|
}
|
|
});
|
|
return product;
|
|
}
|
|
|
|
fillMachine() {
|
|
this.products = require('./products');
|
|
this.enumerateProducts();
|
|
}
|
|
|
|
enumerateProducts() {
|
|
let id = 1;
|
|
this.products.forEach((item) => (item.id = id++));
|
|
}
|
|
|
|
calculateChange(ammount) {
|
|
const availableCoins = [
|
|
0.01,
|
|
0.02,
|
|
0.05,
|
|
0.1,
|
|
0.2,
|
|
0.5,
|
|
1,
|
|
2,
|
|
5
|
|
].reverse();
|
|
let change = [];
|
|
let sum = 0;
|
|
while (sum < ammount) {
|
|
for (let coin of availableCoins) {
|
|
if (sum + coin <= ammount) {
|
|
change.push(coin);
|
|
break;
|
|
}
|
|
}
|
|
sum = change.reduce((acc, curr) => acc + curr);
|
|
}
|
|
return change;
|
|
}
|
|
};
|