Kitchen sink
ECMAScript
// Candy class
class Candy {
/**
* A class representing a type of candy sold in the candy shop.
* @constructor
* @param {string} name - The name of the candy.
* @param {number} price - The price of the candy in dollars.
*/
constructor(name, price) {
this.name = name;
this.price = price;
}
}
// Customer class
class Customer {
/**
* A class representing a customer of the candy shop.
* @constructor
* @param {string} name - The name of the customer.
* @param {number} money - The amount of money the customer has in dollars.
*/
constructor(name, money) {
this.name = name;
this.money = money;
this.cart = [];
}
/**
* Adds a candy to the customer's cart.
* @param {Candy} candy - The candy to add to the cart.
* @param {number} quantity - The quantity of the candy to add to the cart.
*/
addToCart(candy, quantity) {
this.cart.push({ candy: candy, quantity: quantity });
}
/**
* Buys the items in the customer's cart and updates the customer's money and the candy shop's inventory.
* @param {CandyShop} candyShop - The candy shop to buy the items from.
*/
buyItems(candyShop) {
let totalCost = this.calculateTotalCost();
if (totalCost > this.money) {
throw new Error("Not enough money to buy items");
}
for (let item of this.cart) {
let candy = item.candy;
let quantity = item.quantity;
if (candy.quantity < quantity) {
throw new Error(`Not enough ${candy.name} in stock`);
}
candyShop.sellCandy(this, candy);
}
this.money -= totalCost;
this.cart = [];
}
}
// CandyShop class
class CandyShop {
constructor(name, candies) {
this.name = name;
this.candies = candies;
}
/**
* Sells a candy to a customer.
* @param {Customer} customer
* @param {Candy} candy
*/
sellCandy(customer, candy) {
if (! candy) {
throw new Error(`No such candy (${candy.name}) in stock.`);
}
if (customer.money < candy.price) {
throw new Error(`Customer ${customer.name} does not have enough money to buy ${candy.name}.`);
}
this.candies.splice(this.candies.indexOf(candy), 1);
}
}
// Exporting as a module
module.exports = {
Candy,
Customer,
CandyShop
};
// Exporting as named exports
export { Candy, Customer, CandyShop };
// Exporting with a custom name
export { CandyShop as SweetShop };
// Importing with CommonJS
const CandyShop = require("./candy-shop");
// Importing a default export with ES6
import myModule from './myModule.js';
// Importing specific properties or methods
import { Candy, Customer, CandyShop } from "./candy-shop;
// Importing with a custom name
import { myModule as customName } from './myModule.js';
// Importing all exports as an object
import * as allExports from './myModule.js';
// Importing with a dynamic import() function
const dynamicImport = async () => {
const myModule = await import('./myModule.js');
// Use myModule here
}