Skip to content

厦门 天顶星 ​

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'))

Released under the MIT License.