defaultifempty.go 604 B

123456789101112131415161718192021222324252627282930313233
  1. package help
  2. // DefaultIfEmpty returns the elements of the specified sequence
  3. // if the sequence is empty.
  4. func (q Query) DefaultIfEmpty(defaultValue interface{}) Query {
  5. return Query{
  6. Iterate: func() Iterator {
  7. next := q.Iterate()
  8. state := 1
  9. return func() (item interface{}, ok bool) {
  10. switch state {
  11. case 1:
  12. item, ok = next()
  13. if ok {
  14. state = 2
  15. } else {
  16. item = defaultValue
  17. ok = true
  18. state = -1
  19. }
  20. return
  21. case 2:
  22. for item, ok = next(); ok; item, ok = next() {
  23. return
  24. }
  25. return
  26. }
  27. return
  28. }
  29. },
  30. }
  31. }