gods/ranges/range.go

57 lines
906 B
Go
Raw Permalink Normal View History

2024-05-19 21:19:55 +03:00
package ranges
2023-07-09 11:39:35 +03:00
import (
2024-05-19 21:19:55 +03:00
"surdeus.su/core/gods/iters"
2023-07-09 11:39:35 +03:00
cnts "golang.org/x/exp/constraints"
)
type Range[V cnts.Ordered] struct {
start, step, end V
}
// Returns the new Range strucucture with corresponding start, step and end.
// If the values can never reach the end then the function will return nil.
func New[V cnts.Ordered](start, step, end V) *Range[V] {
return &Range[V]{
start, step, end,
}
}
2024-05-19 21:19:55 +03:00
func (r *Range[V]) Chan() iters.PairChan[int, V] {
less := func(a, b V) bool {
return a < b
}
more := func(a, b V) bool {
return a > b
}
var compare func(a, b V) bool
2023-07-09 11:39:35 +03:00
start, step, end := r.start, r.step, r.end
2024-05-19 21:19:55 +03:00
if start < end {
compare = less
} else {
compare = more
}
c := make(iters.PairChan[int, V])
2023-07-09 11:39:35 +03:00
go func(){
j := 0
for i := start ; compare(i, end) ; i += step {
2024-05-19 21:19:55 +03:00
c <- iters.Pair[int, V]{
2023-07-09 11:39:35 +03:00
K:j,
V:i,
}
j++
}
close(c)
}()
return c
}