Skip to content

Instantly share code, notes, and snippets.

@AngeloAnolin
Created July 6, 2024 17:10
Show Gist options
  • Save AngeloAnolin/90fff10273b9e174521e675a65c6a968 to your computer and use it in GitHub Desktop.
Save AngeloAnolin/90fff10273b9e174521e675a65c6a968 to your computer and use it in GitHub Desktop.
interface IFruit {
name: string
qty: number
price: number
}
const FruitStand = () => {
const fruits = new Map<string, IFruit>();
const addFruit = (name: string, qty: number, price: number) => {
if(!fruits.has(name)) {
fruits.set(name, { name, qty, price})
} else {
const existFruit = fruits.get(name)
existFruit.qty += qty
existFruit.price = price
console.log(`The fruit ${name} is already in the list. The new quantity is ${existFruit.qty} and the updated price is ${price.toFixed(2)}`)
}
}
const updateQty = (name: string, qty: number) => {
if(fruits.has(name)) {
fruits.get(name)!.qty = qty
} else {
// Handle fruit not found
console.log(`The fruit ${name} is not yet on the list. Please add it first.`)
}
}
const calcTotalValue = (): number => {
const fruitsArray = Array.from(fruits.values());
const total:number = fruitsArray.reduce((accumulator, { qty, price }) => {
return accumulator + qty * price
}, 0)
return total
}
return {
addFruit,
updateQty,
calcTotalValue
}
}
// Testing
const fs = FruitStand()
// Add fruits
fs.addFruit('Banana', 10, 1.25)
fs.addFruit('Apple', 20, 1.35)
fs.addFruit('Kiwi', 15, 1.55)
//Get initial total value
const initTotalValue = fs.calcTotalValue()
console.log(`The initial value of the fruits is ${initTotalValue.toFixed(2)}`)
// ==> The initial value of the fruits is 62.75
// Update fruits
fs.updateQty('Banana', 5)
fs.updateQty('Kiwi', 3)
// Calculate updated value
const updatedValue = fs.calcTotalValue()
console.log(`The updated value of the fruits is ${updatedValue.toFixed(2)}`)
// ==> The updated value of the fruits is 37.90
// Update with fruit not in the list yet
fs.updateQty('Pear', 5)
// ==> The fruit Pear is not yet on the list. Please add it first.
// Try add a fruit that is already on the list
fs.addFruit('Banana', 10, 1.65)
// ==> The fruit Banana is already in the list. The new quantity is 15 and the updated price is 1.65
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment