Ben Clayton | 475941c | 2022-03-30 21:12:14 +0000 | [diff] [blame] | 1 | // Copyright 2022 The Dawn Authors |
| 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 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package container |
| 16 | |
| 17 | import "sort" |
| 18 | |
| 19 | // Map is a generic unordered map, which wrap's go's builtin 'map'. |
| 20 | // K is the map key, which must match the 'key' constraint. |
| 21 | // V is the map value, which can be any type. |
| 22 | type Map[K key, V any] map[K]V |
| 23 | |
| 24 | // Returns a new empty map |
| 25 | func NewMap[K key, V any]() Map[K, V] { |
| 26 | return make(Map[K, V]) |
| 27 | } |
| 28 | |
| 29 | // Add adds an item to the map. |
| 30 | func (m Map[K, V]) Add(k K, v V) { |
| 31 | m[k] = v |
| 32 | } |
| 33 | |
| 34 | // Remove removes an item from the map |
| 35 | func (m Map[K, V]) Remove(item K) { |
| 36 | delete(m, item) |
| 37 | } |
| 38 | |
| 39 | // Contains returns true if the map contains the given item |
| 40 | func (m Map[K, V]) Contains(item K) bool { |
| 41 | _, found := m[item] |
| 42 | return found |
| 43 | } |
| 44 | |
| 45 | // Keys returns the sorted keys of the map as a slice |
| 46 | func (m Map[K, V]) Keys() []K { |
| 47 | out := make([]K, 0, len(m)) |
| 48 | for v := range m { |
| 49 | out = append(out, v) |
| 50 | } |
| 51 | sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) |
| 52 | return out |
| 53 | } |
| 54 | |
| 55 | // Values returns the values of the map sorted by key |
| 56 | func (m Map[K, V]) Values() []V { |
| 57 | out := make([]V, 0, len(m)) |
| 58 | for _, k := range m.Keys() { |
| 59 | out = append(out, m[k]) |
| 60 | } |
| 61 | return out |
| 62 | } |