30 lines
585 B
Go
30 lines
585 B
Go
package xslices
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"math/big"
|
|
)
|
|
|
|
func ForEach[T any](items []T, f func(T)) {
|
|
for _, item := range items {
|
|
f(item)
|
|
}
|
|
}
|
|
|
|
func AsMap[T any, U comparable](items []T, f func(T) U) map[U]struct{} {
|
|
out := make(map[U]struct{}, len(items))
|
|
ForEach(items, func(in T) {
|
|
out[f(in)] = struct{}{}
|
|
})
|
|
return out
|
|
}
|
|
|
|
func Shuffle[T any](items []T) {
|
|
maxnum := big.NewInt(int64(len(items)))
|
|
for i := range items {
|
|
swapWith, _ := rand.Int(rand.Reader, maxnum)
|
|
swapWithIdx := int(swapWith.Int64())
|
|
items[i], items[swapWithIdx] = items[swapWithIdx], items[i]
|
|
}
|
|
}
|