range.go 906 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package ranges
  2. import (
  3. "surdeus.su/core/gods/iters"
  4. cnts "golang.org/x/exp/constraints"
  5. )
  6. type Range[V cnts.Ordered] struct {
  7. start, step, end V
  8. }
  9. // Returns the new Range strucucture with corresponding start, step and end.
  10. // If the values can never reach the end then the function will return nil.
  11. func New[V cnts.Ordered](start, step, end V) *Range[V] {
  12. return &Range[V]{
  13. start, step, end,
  14. }
  15. }
  16. func (r *Range[V]) Chan() iters.PairChan[int, V] {
  17. less := func(a, b V) bool {
  18. return a < b
  19. }
  20. more := func(a, b V) bool {
  21. return a > b
  22. }
  23. var compare func(a, b V) bool
  24. start, step, end := r.start, r.step, r.end
  25. if start < end {
  26. compare = less
  27. } else {
  28. compare = more
  29. }
  30. c := make(iters.PairChan[int, V])
  31. go func(){
  32. j := 0
  33. for i := start ; compare(i, end) ; i += step {
  34. c <- iters.Pair[int, V]{
  35. K:j,
  36. V:i,
  37. }
  38. j++
  39. }
  40. close(c)
  41. }()
  42. return c
  43. }