-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
map.spice
92 lines (82 loc) · 1.89 KB
/
map.spice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import "std/data/red-black-tree";
// Add generic type definitions
type K dyn;
type V dyn;
/**
* A map in Spice is a commonly used data structure, which can be used to represent a list of key value pairs.
*
* Time complexity:
* Insert: O(log n)
* Delete: O(log n)
* Lookup: O(log n)
*/
public type Map<K, V> struct {
RedBlackTree<K, V> tree
}
/**
* Inserts a key value pair into the map.
*
* @param key The key to insert.
* @param value The value to insert.
*/
public p Map.insert(const K& key, const V& value) {
this.tree.insert(key, value);
}
/**
* Removes a key value pair from the map.
*
* @param key The key to remove.
*/
public p Map.remove(const K& key) {
this.tree.remove(key);
}
/**
* Gets a value from the map.
* Note: If the key is not found in the map, this function will panic. To avoid this, use getSafe instead.
*
* @param key The key to get.
* @return The value associated with the key.
*/
public f<V&> Map.get(const K& key) {
return this.tree.find(key);
}
/**
* Gets a value from the map, returning a result.
*
* @param key The key to get.
* @return The value associated with the key, or an error if the key does not exist.
*/
public f<Result<V>> Map.getSafe(const K& key) {
return this.tree.findSafe(key);
}
/**
* Checks if the map contains a key.
*
* @param key The key to check.
* @return True if the map contains the key, false otherwise.
*/
public f<bool> Map.contains(const K& key) {
return this.tree.contains(key);
}
/**
* Gets the number of elements in the map.
*
* @return The number of elements in the map.
*/
public f<unsigned long> Map.getSize() {
return this.tree.getSize();
}
/**
* Checks if the map is empty.
*
* @return True if the map is empty, false otherwise.
*/
public f<bool> Map.isEmpty() {
return this.tree.getSize() == 0l;
}
/**
* Removes all elements from the map.
*/
public p Map.clear() {
this.tree.clear();
}