puzpuzpuz / xsync

Concurrent data structures for Go
Apache License 2.0
1.13k stars 40 forks source link

[FEATURE REQUEST] - Introduce functions Keys, Values, AsMap, Clone #146

Open oarkflow opened 3 months ago

oarkflow commented 3 months ago

It would be great if there's support for some functions in MapOf and Map like

These functions would be helpful

sujit-baniya commented 3 months ago
// Keys returns a slice of all keys in the map.
func (m *Map[K, V]) Keys() []K {
    keys := make([]K, 0, m.Len())
    m.Range(func(key K, value V) bool {
        keys = append(keys, key)
        return true
    })
    return keys
}

// Values returns a slice of all values in the map.
func (m *Map[K, V]) Values() []V {
    values := make([]V, 0, m.Len())
    m.Range(func(key K, value V) bool {
        values = append(values, value)
        return true
    })
    return values
}

// AsMap returns the entire map as a standard Go map.
func (m *Map[K, V]) AsMap() map[K]V {
    stdMap := make(map[K]V, m.Len())
    m.Range(func(key K, value V) bool {
        stdMap[key] = value
        return true
    })
    return stdMap
}

// Clone creates a deep copy of the map.
func (m *Map[K, V]) Clone() *Map[K, V] {
    clone := NewMap[K, V]()
    m.Range(func(key K, value V) bool {
        clone.Store(key, value)
        return true
    })
    return clone
}
puzpuzpuz commented 3 months ago

All of these functions can be easily implemented over Range. I don't like the idea of having them built-in as they're expensive in many aspects and having them will promote their usage. It's better to have a smaller, but more efficient API surface and let people build on top of it if they need something extra.