Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x | interface Product {
id: string;
name: string;
price: number;
}
/**
* 任務:實作一個函式 `createShoppingCart`,該函式應該能夠創建一個購物車。
* 範例:createShoppingCart() 應該回傳一個購物車物件,該物件應該有 addItem、getTotalPrice、getItemCount 和 clear 等方法
* @returns - 回傳一個購物車物件
*/
export function createShoppingCart() {
let items: Product[] = [];
function addItem(item: Product) {
items.push(item);
}
/**
* getTotalPrice 方法:計算購物車中所有商品的總價
* @returns - 回傳購物車中所有商品的總價
* 範例:getTotalPrice() 應該回傳 300,假設購物車中有兩個商品,價格分別為 100 和 200
*/
function getTotalPrice() {
// 請在此處寫下你的程式碼
return items.reduce((acc, cur) => {
return acc + cur.price;
}, 0);
}
function getItemCount() {
return items.length;
}
function clear() {
items = [];
}
return {
addItem,
getTotalPrice,
getItemCount,
clear
};
} |