| | |
| | | } |
| | | |
| | | func AddMoreUnit(units []models.UnitItems, units2 []models.UnitItems) []models.UnitItems { |
| | | moreValueArr := make([]models.UnitItems, 0, len(units)) |
| | | for _, unitItem1 := range units { |
| | | for _, unitItem2 := range units2 { |
| | | if unitItem1.Unit == unitItem2.Unit { |
| | | moreValueArr = append(moreValueArr, models.UnitItems{ |
| | | Amount: unitItem1.Amount.Add(unitItem2.Amount), |
| | | Unit: unitItem1.Unit, |
| | | Floating: unitItem1.Floating, |
| | | }) |
| | | } |
| | | unitMap := make(map[string]models.UnitItems) |
| | | |
| | | // 将 units 中的所有元素添加到 map 中 |
| | | for _, unitItem := range units { |
| | | unitMap[unitItem.Unit] = unitItem |
| | | } |
| | | |
| | | // 遍历 units2,合并相同单位的数量,并将 units2 中不存在于 units 中的单位添加到 map 中 |
| | | for _, unitItem2 := range units2 { |
| | | if unitItem1, exists := unitMap[unitItem2.Unit]; exists { |
| | | unitItem1.Amount = unitItem1.Amount.Add(unitItem2.Amount) |
| | | unitMap[unitItem2.Unit] = unitItem1 |
| | | } else { |
| | | unitMap[unitItem2.Unit] = unitItem2 |
| | | } |
| | | } |
| | | |
| | | // 将 map 转换回 slice |
| | | moreValueArr := make([]models.UnitItems, 0, len(unitMap)) |
| | | for _, unitItem := range unitMap { |
| | | moreValueArr = append(moreValueArr, unitItem) |
| | | } |
| | | |
| | | return moreValueArr |
| | | } |
| | | |