goutils/containers/generics.go

35 lines
873 B
Go
Raw Normal View History

2023-08-18 15:13:53 +00:00
package containers
type ChainElem[T any] struct {
Elem *T
Next *ChainElem[T]
}
// reachable checks if you can reach elem l when starting from elem f.
// It detects loops and returns false if it runs into one.
func reachable[T any](f, l *ChainElem[T]) bool {
// Map to keep track of nodes already visited
checks := make(map[*ChainElem[T]]bool)
for w := f; w != l; w = w.Next {
if w == nil {
return false
}
// Shortcut: Maps where the value is bool have a default value of false
// If a key doesn't exist yet the result will thus be false
if checks[w] {
return false
}
// Set the current elem to true to mark it as visited
checks[w] = true
}
return true
}
// emptyElem creates a new ChainElem[T] with empty values.
func emptyElem[T any]() *ChainElem[T] {
return &ChainElem[T]{
Elem: nil,
Next: nil,
}
}