concat.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package help
  2. // Append inserts an item to the end of a collection, so it becomes the last
  3. // item.
  4. func (q Query) Append(item interface{}) Query {
  5. return Query{
  6. Iterate: func() Iterator {
  7. next := q.Iterate()
  8. appended := false
  9. return func() (interface{}, bool) {
  10. i, ok := next()
  11. if ok {
  12. return i, ok
  13. }
  14. if !appended {
  15. appended = true
  16. return item, true
  17. }
  18. return nil, false
  19. }
  20. },
  21. }
  22. }
  23. // Concat concatenates two collections.
  24. //
  25. // The Concat method differs from the Union method because the Concat method
  26. // returns all the original elements in the input sequences. The Union method
  27. // returns only unique elements.
  28. func (q Query) Concat(q2 Query) Query {
  29. return Query{
  30. Iterate: func() Iterator {
  31. next := q.Iterate()
  32. next2 := q2.Iterate()
  33. use1 := true
  34. return func() (item interface{}, ok bool) {
  35. if use1 {
  36. item, ok = next()
  37. if ok {
  38. return
  39. }
  40. use1 = false
  41. }
  42. return next2()
  43. }
  44. },
  45. }
  46. }
  47. // Prepend inserts an item to the beginning of a collection, so it becomes the
  48. // first item.
  49. func (q Query) Prepend(item interface{}) Query {
  50. return Query{
  51. Iterate: func() Iterator {
  52. next := q.Iterate()
  53. prepended := false
  54. return func() (interface{}, bool) {
  55. if prepended {
  56. return next()
  57. }
  58. prepended = true
  59. return item, true
  60. }
  61. },
  62. }
  63. }