• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

enetx / g / 14821882949

04 May 2025 01:51PM UTC coverage: 87.23% (+0.9%) from 86.333%
14821882949

push

github

enetx
unsafe ref

4 of 4 new or added lines in 1 file covered. (100.0%)

74 existing lines in 10 files now uncovered.

3347 of 3837 relevant lines covered (87.23%)

132.15 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.96
/map_ordered.go
1
package g
2

3
import (
4
        "fmt"
5
        "slices"
6

7
        "github.com/enetx/g/cmp"
8
        "github.com/enetx/g/f"
9
        "github.com/enetx/g/pkg/rand"
10
)
11

12
// NewMapOrd creates a new ordered Map with the specified size (if provided).
13
// An ordered Map is an Map that maintains the order of its key-value pairs based on the
14
// insertion order. If no size is provided, the default size will be used.
15
//
16
// Parameters:
17
//
18
// - size ...int: (Optional) The initial size of the ordered Map. If not provided, a default size
19
// will be used.
20
//
21
// Returns:
22
//
23
// - MapOrd[K, V]: Ordered Map with the specified initial size (or default
24
// size if not provided).
25
//
26
// Example usage:
27
//
28
//        mapOrd := g.NewMapOrd[string, int](10)
29
//
30
// Creates a new ordered Map with an initial size of 10.
31
func NewMapOrd[K, V any](size ...Int) MapOrd[K, V] {
112✔
32
        return make(MapOrd[K, V], 0, Slice[Int](size).Get(0).Some())
112✔
33
}
112✔
34

35
// Transform applies a transformation function to the MapOrd and returns the result.
36
func (mo MapOrd[K, V]) Transform(fn func(MapOrd[K, V]) MapOrd[K, V]) MapOrd[K, V] { return fn(mo) }
2✔
37

38
// AsAny converts each key-value pair in the MapOrd to the 'any' type.
39
// It returns a new MapOrd[any, any], where both keys and values are of type 'any'.
40
// This is especially useful for working with dynamic formatting tools like Sprintf,
41
// where modifiers such as $get can access elements without strict typing constraints.
42
//
43
// Example:
44
//
45
//        mo := NewMapOrd[string, int]()
46
//        mo.
47
//                Set("a", 1).
48
//                Set("b", 2)
49
//
50
//        Printf("{1.$get(a)} -> {1.$get(b)}\n", mo.AsAny())
51
//        // Output: "a -> 1"
UNCOV
52
func (mo MapOrd[K, V]) AsAny() MapOrd[any, any] {
×
UNCOV
53
        anymo := make([]Pair[any, any], mo.Len())
×
UNCOV
54

×
55
        for i, v := range mo {
×
56
                anymo[i] = Pair[any, any]{v.Key, v.Value}
×
57
        }
×
58

59
        return anymo
×
60
}
61

62
// Iter returns an iterator (SeqMapOrd[K, V]) for the ordered Map, allowing for sequential iteration
63
// over its key-value pairs. It is commonly used in combination with higher-order functions,
64
// such as 'ForEach', to perform operations on each key-value pair of the ordered Map.
65
//
66
// Returns:
67
//
68
// A SeqMapOrd[K, V], which can be used for sequential iteration over the key-value pairs of the ordered Map.
69
//
70
// Example usage:
71
//
72
//        iter := g.NewMapOrd[int, int]()
73
//        iter.
74
//                Set(1, 1).
75
//                Set(2, 2).
76
//                Set(3, 3).
77
//                Iter()
78
//
79
//        iter.ForEach(func(k, v int) {
80
//            // Process key-value pair
81
//        })
82
//
83
// The 'Iter' method provides a convenient way to traverse the key-value pairs of an ordered Map
84
// in a functional style, enabling operations like mapping or filtering.
85
func (mo MapOrd[K, V]) Iter() SeqMapOrd[K, V] { return seqMapOrd(mo) }
45✔
86

87
// IntoIter returns a consuming iterator (SeqMapOrd[K, V]) for the ordered Map,
88
// transferring ownership of its key-value pairs and clearing the original MapOrd.
89
//
90
// After calling IntoIter, the original MapOrd is emptied and should not be reused
91
// unless reassigned or repopulated.
92
//
93
// Returns:
94
//
95
// A SeqMapOrd[K, V], yielding all key-value pairs in insertion order, consuming them in the process.
96
//
97
// Example usage:
98
//
99
//        m := g.NewMapOrd[string, int]()
100
//        m.Set("a", 1)
101
//        m.Set("b", 2)
102
//
103
//        iter := m.IntoIter()
104
//        m.Len() // 0
105
//
106
//        iter.ForEach(func(k string, v int) {
107
//            fmt.Println(k, v)
108
//        })
109
func (mo *MapOrd[K, V]) IntoIter() SeqMapOrd[K, V] {
1✔
110
        data := *mo
1✔
111
        *mo = nil
1✔
112

1✔
113
        return seqMapOrd(data)
1✔
114
}
1✔
115

116
// IterReverse returns an iterator (SeqMapOrd[K, V]) for the ordered Map that allows for sequential iteration
117
// over its key-value pairs in reverse order. This method is useful when you need to process the elements
118
// from the last to the first.
119
//
120
// Returns:
121
//
122
// A SeqMapOrd[K, V], which can be used for sequential iteration over the key-value pairs of the ordered Map in reverse order.
123
//
124
// Example usage:
125
//
126
//        iter := g.NewMapOrd[int, int]()
127
//        iter.
128
//                Set(1, 1).
129
//                Set(2, 2).
130
//                Set(3, 3).
131
//                IterReverse()
132
//
133
//        iter.ForEach(func(k, v int) {
134
//            // Process key-value pair in reverse order
135
//            fmt.Println("Key:", k, "Value:", v)
136
//        })
137
//
138
// The 'IterReverse' method complements the 'Iter' method by providing a way to access the elements
139
// in a reverse sequence, offering additional flexibility in data processing scenarios.
140
func (mo MapOrd[K, V]) IterReverse() SeqMapOrd[K, V] { return revSeqMapOrd(mo) }
3✔
141

142
// MapOrdFromStd converts a standard Go map to an ordered Map.
143
// The resulting ordered Map will maintain the order of its key-value pairs based on the order of
144
// insertion.
145
// This function is useful when you want to create an ordered Map from an existing Go map.
146
//
147
// Parameters:
148
//
149
// - m map[K]V: The input Go map to be converted to an ordered Map.
150
//
151
// Returns:
152
//
153
// - MapOrd[K, V]: New ordered Map containing the same key-value pairs as the
154
// input Go map.
155
//
156
// Example usage:
157
//
158
//        mapOrd := g.MapOrdFromStd[string, int](goMap)
159
//
160
// Converts the standard Go map 'map[K]V' to an ordered Map.
161
func MapOrdFromStd[K comparable, V any](m map[K]V) MapOrd[K, V] { return Map[K, V](m).ToMapOrd() }
2✔
162

163
// SortBy sorts the ordered Map by a custom comparison function.
164
//
165
// Parameters:
166
//
167
// - fn func(a, b Pair[K, V]) cmp.Ordering: The custom comparison function used for sorting the ordered Map.
168
//
169
// Example usage:
170
//
171
//        hmapo.SortBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Key.Cmp(b.Key) })
172
//        hmapo.SortBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Value.Cmp(b.Value) })
173
func (mo MapOrd[K, V]) SortBy(fn func(a, b Pair[K, V]) cmp.Ordering) {
5✔
174
        slices.SortFunc(mo, func(a, b Pair[K, V]) int { return int(fn(a, b)) })
28✔
175
}
176

177
// SortByKey sorts the ordered MapOrd[K, V] by the keys using a custom comparison function.
178
//
179
// Parameters:
180
//
181
// - fn func(a, b K) cmp.Ordering: The custom comparison function used for sorting the keys.
182
//
183
// Example usage:
184
//
185
//        hmapo.SortByKey(func(a, b g.String) cmp.Ordering { return a.Cmp(b) })
186
func (mo MapOrd[K, V]) SortByKey(fn func(a, b K) cmp.Ordering) {
6✔
187
        slices.SortFunc(mo, func(a, b Pair[K, V]) int { return int(fn(a.Key, b.Key)) })
31✔
188
}
189

190
// SortByValue sorts the ordered MapOrd[K, V] by the values using a custom comparison function.
191
//
192
// Parameters:
193
//
194
// - fn func(a, b V) cmp.Ordering: The custom comparison function used for sorting the values.
195
//
196
// Example usage:
197
//
198
//        hmapo.SortByValue(func(a, b g.Int) cmp.Ordering { return a.Cmp(b) })
199
func (mo MapOrd[K, V]) SortByValue(fn func(a, b V) cmp.Ordering) {
2✔
200
        slices.SortFunc(mo, func(a, b Pair[K, V]) int { return int(fn(a.Value, b.Value)) })
6✔
201
}
202

203
// Clone creates a new ordered Map with the same key-value pairs.
204
func (mo MapOrd[K, V]) Clone() MapOrd[K, V] {
3✔
205
        result := NewMapOrd[K, V](mo.Len())
3✔
206
        mo.Iter().ForEach(func(k K, v V) { result.Set(k, v) })
11✔
207

208
        return result
3✔
209
}
210

211
// Copy copies key-value pairs from the source ordered Map to the current ordered Map.
212
func (mo *MapOrd[K, V]) Copy(src MapOrd[K, V]) { src.Iter().ForEach(func(k K, v V) { mo.Set(k, v) }) }
4✔
213

214
// ToMap converts the ordered Map to a standard Map.
215
// func (mo MapOrd[K, V]) ToMap() Map[K, V] {
216
//         m := NewMap[K, V](len(mo))
217
//         mo.Iter().ForEach(func(k K, v V) { m.Set(k, v) })
218
//
219
//         return m
220
// }
221

222
// Set sets the value for the specified key in the ordered Map.
223
func (mo *MapOrd[K, V]) Set(key K, value V) {
315✔
224
        if i := mo.index(key); i != -1 {
322✔
225
                (*mo)[i].Value = value
7✔
226
                return
7✔
227
        }
7✔
228

229
        mp := Pair[K, V]{key, value}
308✔
230
        *mo = append(*mo, mp)
308✔
231
}
232

233
// Get retrieves the value for the specified key, along with a boolean indicating whether the key
234
// was found in the ordered Map. This function is useful when you want to access the value
235
// associated with a key in the ordered Map, and also check if the key exists in the map.
236
//
237
// Parameters:
238
//
239
// - key K: The key to search for in the ordered Map.
240
//
241
// Returns:
242
//
243
// - V: The value associated with the specified key if found, or the zero value for the value type
244
// if the key is not found.
245
//
246
// - bool: A boolean value indicating whether the key was found in the ordered Map.
247
//
248
// Example usage:
249
//
250
//        value, found := mo.Get("some_key")
251
//
252
// Retrieves the value associated with the key "some_key" and checks if the key exists in the
253
// ordered Map.
254
func (mo MapOrd[K, V]) Get(key K) Option[V] {
27✔
255
        if i := mo.index(key); i != -1 {
44✔
256
                return Some(mo[i].Value)
17✔
257
        }
17✔
258

259
        return None[V]()
10✔
260
}
261

262
// Shuffle randomly reorders the elements of the ordered Map.
263
// It operates in place and affects the original order of the map's entries.
264
//
265
// The function uses the crypto/rand package to generate random indices.
266
func (mo MapOrd[K, V]) Shuffle() {
1✔
267
        for i := mo.Len() - 1; i > 0; i-- {
5✔
268
                j := rand.N(i + 1)
4✔
269
                mo[i], mo[j] = mo[j], mo[i]
4✔
270
        }
4✔
271
}
272

273
// GetOrSet returns the value for a key. If the key does not exist, it returns the default value
274
// instead and also sets the default value for the key in the ordered Map. This function is useful
275
// when you want to access the value associated with a key in the ordered Map, and if the key does
276
// not exist, you want to return a specified default value and set that default value for the key.
277
//
278
// Parameters:
279
//
280
// - key K: The key to search for in the ordered Map.
281
//
282
// - defaultValue V: The default value to return if the key is not found in the ordered Map.
283
// If the key is not found, this default value will also be set for the key in the ordered Map.
284
//
285
// Returns:
286
//
287
// - V: The value associated with the specified key if found, or the provided default value if the key is not found.
288
//
289
// Example usage:
290
//
291
//        value := mo.GetOrSet("some_key", "default_value")
292
//
293
// Retrieves the value associated with the key "some_key" or returns "default_value" if the key is
294
// not found, and sets "default_value" as the value for "some_key" in the ordered Map if it's not
295
// present.
296
func (mo *MapOrd[K, V]) GetOrSet(key K, defaultValue V) V {
2✔
297
        if value := mo.Get(key); value.IsSome() {
3✔
298
                return value.Some()
1✔
299
        }
1✔
300

301
        mo.Set(key, defaultValue)
1✔
302

1✔
303
        return defaultValue
1✔
304
}
305

306
// Invert inverts the key-value pairs in the ordered Map, creating a new ordered Map with the
307
// values as keys and the original keys as values.
308
func (mo MapOrd[K, V]) Invert() MapOrd[V, K] {
2✔
309
        result := NewMapOrd[V, K](mo.Len())
2✔
310
        mo.Iter().ForEach(func(k K, v V) { result.Set(v, k) })
5✔
311

312
        return result
2✔
313
}
314

315
func (mo MapOrd[K, V]) index(key K) int {
406✔
316
        if f.IsComparable(key) {
810✔
317
                for i, mp := range mo {
1,028✔
318
                        if f.Eq[any](mp.Key)(key) {
706✔
319
                                return i
82✔
320
                        }
82✔
321
                }
322

323
                return -1
322✔
324
        }
325

326
        for i, mp := range mo {
3✔
327
                if f.Eqd(mp.Key)(key) {
2✔
328
                        return i
1✔
329
                }
1✔
330
        }
331

332
        return -1
1✔
333
}
334

335
// Keys returns an Slice containing all the keys in the ordered Map.
336
func (mo MapOrd[K, V]) Keys() Slice[K] { return mo.Iter().Keys().Collect() }
2✔
337

338
// Values returns an Slice containing all the values in the ordered Map.
339
func (mo MapOrd[K, V]) Values() Slice[V] { return mo.Iter().Values().Collect() }
2✔
340

341
// Delete removes the specified keys from the ordered Map.
342
func (mo *MapOrd[K, V]) Delete(keys ...K) {
7✔
343
        for _, key := range keys {
18✔
344
                if i := mo.index(key); i != -1 {
18✔
345
                        *mo = slices.Delete(*mo, i, i+1)
7✔
346
                }
7✔
347
        }
348
}
349

350
// Eq compares the current ordered Map to another ordered Map and returns true if they are equal.
351
func (mo MapOrd[K, V]) Eq(other MapOrd[K, V]) bool {
22✔
352
        n := len(mo)
22✔
353

22✔
354
        if n != len(other) {
24✔
355
                return false
2✔
356
        }
2✔
357

358
        if n == 0 {
23✔
359
                return true
3✔
360
        }
3✔
361

362
        comparable := f.IsComparable(mo[0].Value)
17✔
363

17✔
364
        for i, mp := range mo {
64✔
365
                if other.index(mp.Key) != i {
48✔
366
                        return false
1✔
367
                }
1✔
368

369
                value := other[i].Value
46✔
370

46✔
371
                if comparable && !f.Eq[any](value)(mp.Value) || !comparable && !f.Eqd(value)(mp.Value) {
47✔
372
                        return false
1✔
373
                }
1✔
374
        }
375

376
        return true
15✔
377
}
378

379
// String returns a string representation of the ordered Map.
380
func (mo MapOrd[K, V]) String() string {
2✔
381
        builder := NewBuilder()
2✔
382

2✔
383
        mo.Iter().ForEach(func(k K, v V) { builder.Write(Format("{}:{}, ", k, v)) })
5✔
384

385
        return builder.String().StripSuffix(", ").Format("MapOrd\\{{}\\}").Std()
2✔
386
}
387

388
// Clear removes all key-value pairs from the ordered Map.
389
func (mo *MapOrd[K, V]) Clear() { mo.Delete(mo.Keys()...) }
2✔
390

391
// Contains checks if the ordered Map contains the specified key.
392
func (mo MapOrd[K, V]) Contains(key K) bool { return mo.index(key) >= 0 }
6✔
393

394
// Empty checks if the ordered Map is empty.
395
func (mo MapOrd[K, V]) Empty() bool { return len(mo) == 0 }
4✔
396

397
// Len returns the number of key-value pairs in the ordered Map.
398
func (mo MapOrd[K, V]) Len() Int { return Int(len(mo)) }
18✔
399

400
// Ne compares the current ordered Map to another ordered Map and returns true if they are not
401
// equal.
402
func (mo MapOrd[K, V]) Ne(other MapOrd[K, V]) bool { return !mo.Eq(other) }
8✔
403

404
// NotEmpty checks if the ordered Map is not empty.
405
func (mo MapOrd[K, V]) NotEmpty() bool { return !mo.Empty() }
2✔
406

407
// Print writes the key-value pairs of the MapOrd to the standard output (console)
408
// and returns the MapOrd unchanged.
UNCOV
409
func (mo MapOrd[K, V]) Print() MapOrd[K, V] { fmt.Print(mo); return mo }
×
410

411
// Println writes the key-value pairs of the MapOrd to the standard output (console) with a newline
412
// and returns the MapOrd unchanged.
UNCOV
413
func (mo MapOrd[K, V]) Println() MapOrd[K, V] { fmt.Println(mo); return mo }
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc