厦门 天顶星
2023-05-09 13:00
- 自我介绍
- async await
- ts相对于js的优势
- redux mobx
ts
/*
You're working on a new feature for an online marketplace that needs to keep track of the items in the shopping cart. Each item is represented as an object with a name, price, and quantity. At any given time, you should be able to perform the following operations:
1. addItem(item: Item): void - Add an item to the shopping cart. If the item already exists in the cart, you should update the quantity.
2. removeItem(itemName: string): void - Remove an item from the shopping cart by its name.
3. getTotal(): number - Get the total cost of the items in the shopping cart.
4. getItemQuantity(itemName: string): number - Get the quantity of a specific item in the shopping cart.
*/
interface Item {
name: string
price: number
quantity: number
}
class ShopCart {
list: Item[] = []
addItem(item: Item) {
let isHave = false
this.list.forEach(i => {
if(i.name === item.name) {
i.quantity += item.quantity
isHave = true
}
})
if(!isHave) {
this.list.push(item)
}
}
removeItem(item: Item) {
this.list.forEach(i => {
if(i.name === item.name) {
i.quantity = i.quantity - item.quantity
}
})
}
clearItem(name: string) {
let index = -1
this.list.forEach((item, idx) => {
if(item.name === name) {
index = idx
}
})
if(index !== -1){
this.list.splice(index, 1)
}
}
getTotal() {
let total = 0
console.log(this.list)
this.list.forEach(item => {
total += item.price * item.quantity
})
return total
}
getItemQuantity(name: string) {
let quantity = 0
this.list.forEach(item => {
if (item.name === name) {
quantity = item.quantity
}
})
return quantity;
}
}
const shopCart = new ShopCart()
const obj: Item = {
name: '1',
price: 10,
quantity: 2
}
const obj2: Item = {
name: '2',
price: 11,
quantity: 1
}
shopCart.addItem(obj)
shopCart.addItem(obj2)
shopCart.addItem(obj)
shopCart.removeItem(obj2)
console.log(shopCart.getTotal())
console.log(shopCart.getItemQuantity('1'))
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89