|
| 1 | +// Copyright 2025 PingCAP, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package maputil |
| 15 | + |
| 16 | +import "maps" |
| 17 | + |
| 18 | +// Merge merges all maps to a new one. |
| 19 | +func Merge[K comparable, V any](maps ...map[K]V) map[K]V { |
| 20 | + return MergeTo(nil, maps...) |
| 21 | +} |
| 22 | + |
| 23 | +// MergeTo merges all maps to the original one. |
| 24 | +func MergeTo[K comparable, V any](original map[K]V, ms ...map[K]V) map[K]V { |
| 25 | + if original == nil { |
| 26 | + original = make(map[K]V) |
| 27 | + } |
| 28 | + for _, m := range ms { |
| 29 | + maps.Copy(original, m) |
| 30 | + } |
| 31 | + return original |
| 32 | +} |
| 33 | + |
| 34 | +// AreEqual checks if two maps are equal. |
| 35 | +func AreEqual[K comparable](map1, map2 map[K]string) bool { |
| 36 | + if len(map1) != len(map2) { |
| 37 | + return false |
| 38 | + } |
| 39 | + for k, v1 := range map1 { |
| 40 | + v2, ok := map2[k] |
| 41 | + if !ok || v1 != v2 { |
| 42 | + return false |
| 43 | + } |
| 44 | + } |
| 45 | + return true |
| 46 | +} |
| 47 | + |
| 48 | +// Select returns a new map with selected keys and values of the originalMap |
| 49 | +func Select[K comparable, V any](originalMap map[K]V, keys ...K) map[K]V { |
| 50 | + ret := make(map[K]V) |
| 51 | + |
| 52 | + for _, k := range keys { |
| 53 | + v, ok := originalMap[k] |
| 54 | + if ok { |
| 55 | + ret[k] = v |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return ret |
| 60 | +} |
0 commit comments