Debian Codegraph @

maps/hashmap/hashmap.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package hashmap implements a map backed by a hash table.
6 //
7 // Elements are unordered in the map.
8 //
9 // Structure is not thread safe.
10 //
11 // Reference: http://en.wikipedia.org/wiki/Associative_array
12 package hashmap
13
14 import (
15 "fmt"
16
17 "github.com/emirpasic/gods/v2/maps"
18 )
19
20 // Assert Map implementation
21 var _ maps.Map[string, int] = (*Map[string, int])(nil)
22
23 // Map holds the elements in go's native map
24 type Map[K comparable, V any] struct {
25 m map[K]V
26 }
27
28 // New instantiates a hash map.
29 func New[K comparable, V any]() *Map[K, V] {
30 return &Map[K, V]{m: make(map[K]V)}
31 }
32
33 // Put inserts element into the map.
34 func (m *Map[K, V]) Put(key K, value V) {
35 m.m[key] = value
36 }
37
38 // Get searches the element in the map by key and returns its value or nil if key is not found in map.
39 // Second return parameter is true if key was found, otherwise false.
40 func (m *Map[K, V]) Get(key K) (value V, found bool) {
41 value, found = m.m[key]
42 return
43 }
44
45 // Remove removes the element from the map by key.
46 func (m *Map[K, V]) Remove(key K) {
47 delete(m.m, key)
48 }
49
50 // Empty returns true if map does not contain any elements
51 func (m *Map[K, V]) Empty() bool {
52 return m.Size() == 0
53 }
54
55 // Size returns number of elements in the map.
56 func (m *Map[K, V]) Size() int {
57 return len(m.m)
58 }
59
60 // Keys returns all keys (random order).
61 func (m *Map[K, V]) Keys() []K {
62 keys := make([]K, m.Size())
63 count := 0
64 for key := range m.m {
65 keys[count] = key
66 count++
67 }
68 return keys
69 }
70
71 // Values returns all values (random order).
72 func (m *Map[K, V]) Values() []V {
73 values := make([]V, m.Size())
74 count := 0
75 for _, value := range m.m {
76 values[count] = value
77 count++
78 }
79 return values
80 }
81
82 // Clear removes all elements from the map.
83 func (m *Map[K, V]) Clear() {
84 clear(m.m)
85 }
86
87 // String returns a string representation of container
88 func (m *Map[K, V]) String() string {
89 str := "HashMap\n"
90 str += fmt.Sprintf("%v", m.m)
91 return str
92 }