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

enetx / g / 14661178371

25 Apr 2025 09:14AM UTC coverage: 86.248% (-0.2%) from 86.478%
14661178371

push

github

enetx
ref

124 of 174 new or added lines in 13 files covered. (71.26%)

1 existing line in 1 file now uncovered.

3462 of 4014 relevant lines covered (86.25%)

127.49 hits per line

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

92.04
/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] {
113✔
32
        return make(MapOrd[K, V], 0, Slice[Int](size).Get(0).Some())
113✔
33
}
113✔
34

35
// Ptr returns a pointer to the current MapOrd value.
36
func (mo MapOrd[K, V]) Ptr() *MapOrd[K, V] { return &mo }
1✔
37

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

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

×
58
        for i, v := range mo {
×
59
                anymo[i] = Pair[any, any]{v.Key, v.Value}
×
60
        }
×
61

62
        return anymo
×
63
}
64

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

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

1✔
116
        return seqMapOrd(data)
1✔
117
}
1✔
118

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

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

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

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

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

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

211
        return result
3✔
212
}
213

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

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

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

232
        mp := Pair[K, V]{key, value}
309✔
233
        *mo = append(*mo, mp)
309✔
234
}
235

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

262
        return None[V]()
10✔
263
}
264

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

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

304
        mo.Set(key, defaultValue)
1✔
305

1✔
306
        return defaultValue
1✔
307
}
308

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

315
        return result
2✔
316
}
317

318
func (mo MapOrd[K, V]) index(key K) int {
409✔
319
        if f.IsComparable(key) {
816✔
320
                for i, mp := range mo {
1,034✔
321
                        if f.Eq[any](mp.Key)(key) {
711✔
322
                                return i
84✔
323
                        }
84✔
324
                }
325

326
                return -1
323✔
327
        }
328

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

335
        return -1
1✔
336
}
337

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

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

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

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

22✔
357
        if n != len(other) {
24✔
358
                return false
2✔
359
        }
2✔
360

361
        if n == 0 {
23✔
362
                return true
3✔
363
        }
3✔
364

365
        comparable := f.IsComparable(mo[0].Value)
17✔
366

17✔
367
        for i, mp := range mo {
65✔
368
                if other.index(mp.Key) != i {
49✔
369
                        return false
1✔
370
                }
1✔
371

372
                value := other[i].Value
47✔
373

47✔
374
                if comparable && !f.Eq[any](value)(mp.Value) || !comparable && !f.Eqd(value)(mp.Value) {
48✔
375
                        return false
1✔
376
                }
1✔
377
        }
378

379
        return true
15✔
380
}
381

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

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

388
        return builder.String().StripSuffix(", ").Format("MapOrd\\{{}\\}").Std()
2✔
389
}
390

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

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

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

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

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

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

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

414
// Println writes the key-value pairs of the MapOrd to the standard output (console) with a newline
415
// and returns the MapOrd unchanged.
NEW
416
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