feat(gslice): add ToBoolMap to collect slice elements into a set (map[T]bool)#20
Conversation
ToSet converts a slice of comparable elements into a set-like map[T]bool, deduplicating elements and enabling fast membership checks. Supports any comparable type including struct, alias, etc.
10ada7e to
82e9830
Compare
| // The element type T must be comparable, as required by Go map keys. | ||
| // | ||
| // 💡 AKA: setOf(...) in Kotlin, .toSet() in Python | ||
| func ToSet[T comparable](s []T) map[T]bool { |
There was a problem hiding this comment.
We already have a collection/set data type, the name ToSet may be misleading. I prefer using ToBoolMap, as we already have ToMap function, and in the future we may add ToStructMap for returning map[V]strcut{}.
There was a problem hiding this comment.
Makes sense — my initial thought was to mirror naming from languages like Kotlin/Python (toSet), but I can see how ToBoolMap better aligns with our existing ToMap and avoids potential confusion with collection/set. I've updated the name accordingly.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #20 +/- ##
==========================================
+ Coverage 95.79% 95.92% +0.13%
==========================================
Files 34 34
Lines 4443 4445 +2
==========================================
+ Hits 4256 4264 +8
+ Misses 144 139 -5
+ Partials 43 42 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
…ribe its behavior and usage, including examples and notes about type requirements.
SilverRainZ
left a comment
There was a problem hiding this comment.
Thanks for your contribution.
Add ToSet for converting slice to map[T]bool
What
This PR adds a generic utility function ToSet, which converts a slice of comparable elements into a map[T]bool — commonly used in Go as a set.
It builds on top of ToMap but provides a more ergonomic API for a frequent use case.
Why
In Go, it’s common to use map[T]bool as a set. While ToMap can technically be used to construct such sets:
ToMap(s, func(x T) (T, bool) { return x, true })
this approach is verbose and repetitive, especially for a pattern that’s so frequently needed in practice.
ToSet eliminates the need for writing an anonymous function every time, and makes the intent clearer at callsite.
Motivation
• toSet() in Python
• setOf() in Kotlin