1、做一个简易的自动售货系统,售货柜中有若干种商品,每种商品有名称(name)、价格(price)、 库存(stock) 三个属性。实现以下功能。
- 售货柜可以列出当前的所有商品,每种商品显示各自的名称、库存和价格。
- 给售货柜补货,即给指定名称的商品添加一定数量的库存。
- 销售商品,给定商品的名称和数量以及顾客预支配金额,判断金额是否足够,若不够则进行提醒,若足够则减库存并找零。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>售货柜</title>
</head>
<script>
let Product = function (name, price, stock) {
this.name = name;
this.price = price;
this.stock = stock;
this.addStock = function(quantity) {
this.stock += quantity;
}
this.show = function(){
console.log(`${this.name}, ${this.price}元, ${this.stock}件`);
}
}
let SellingMachine = function () {
this.products = [
new Product('Coca Cola',3,10),
new Product('honey',27,17),
new Product('herb juice',6,12)
];
this.list = function() {
console.log(`销售以下商品:`);
this.products.forEach(m => m.show());
}
this.replenishment = function(name, quantity){
if (quantity <= 0) {
throw new Error('quantity必须大于0');
}
const product = this.products.find(x => x.name == name);
if (product === undefined) {
console.log(`不销售${name}`);
return;
}
product.addStock(quantity);
console.log(`补货成功,${product.name}剩余${product.stock}件`);
}
this.sell = function(name, quantity, money) {
const product = this.products.find(x => x.name == name);
if (product === undefined) {
console.log(`不销售${name}`);
return;
}
if (product.stock < quantity) {
console.log(`库存不足,${product.name} 仅剩 ${product.stock} 件`);
return;
}
const totalPrice = quantity * product.price;
if (money < totalPrice) {
console.log(`金额不足,${name} ${quantity}件应付¥${totalPrice}`);
return;
}
product.addStock(-quantity);
const rest = money - totalPrice;
console.log(`成功购买商品:${name}, ${quantity}件, 共${totalPrice}元,请取走您的商品。${rest>0?`以及零钱${rest}元。`:''}`);
return rest;
}
}
const machine = new SellingMachine();
machine.list();
machine.sell('西瓜');
machine.sell('herb juice',6,12);
machine.replenishment('herb juice', 20);
machine.list();
</script>
<body>
</body>
</html>