ring.go 646 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package collection
  2. type Ring struct {
  3. elements []interface{}
  4. index int
  5. }
  6. func NewRing(n int) *Ring {
  7. if n < 1 {
  8. panic("n should be greater than 0")
  9. }
  10. return &Ring{
  11. elements: make([]interface{}, n),
  12. }
  13. }
  14. func (r *Ring) Add(v interface{}) {
  15. r.elements[r.index%len(r.elements)] = v
  16. r.index++
  17. }
  18. func (r *Ring) Take() []interface{} {
  19. var size int
  20. var start int
  21. if r.index > len(r.elements) {
  22. size = len(r.elements)
  23. start = r.index % len(r.elements)
  24. } else {
  25. size = r.index
  26. }
  27. elements := make([]interface{}, size)
  28. for i := 0; i < size; i++ {
  29. elements[i] = r.elements[(start+i)%len(r.elements)]
  30. }
  31. return elements
  32. }