-
Notifications
You must be signed in to change notification settings - Fork 223
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Cleiton Marques Souza <[email protected]>
- Loading branch information
1 parent
7a0b206
commit 55c110a
Showing
3 changed files
with
128 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package linq | ||
|
||
// DefaultIfEmpty returns the elements of the specified sequence | ||
// if the sequence is empty. | ||
func (q Query) DefaultIfEmpty(defaultValue interface{}) Query { | ||
return Query{ | ||
Iterate: func() Iterator { | ||
next := q.Iterate() | ||
state := 1 | ||
|
||
return func() (item interface{}, ok bool) { | ||
switch state { | ||
case 1: | ||
item, ok = next() | ||
if ok { | ||
state = 2 | ||
} else { | ||
item = defaultValue | ||
ok = true | ||
state = -1 | ||
} | ||
return | ||
case 2: | ||
for item, ok = next(); ok; item, ok = next() { | ||
return | ||
} | ||
return | ||
} | ||
return | ||
} | ||
}, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package linq | ||
|
||
import ( | ||
"testing" | ||
) | ||
|
||
func TestDefaultIfEmpty(t *testing.T) { | ||
defaultValue := 0 | ||
tests := []struct { | ||
input []interface{} | ||
want []interface{} | ||
}{ | ||
{[]interface{}{}, []interface{}{defaultValue}}, | ||
{[]interface{}{1, 2, 3, 4, 5}, []interface{}{1, 2, 3, 4, 5}}, | ||
} | ||
|
||
for _, test := range tests { | ||
q := From(test.input).DefaultIfEmpty(defaultValue) | ||
|
||
if !validateQuery(q, test.want) { | ||
t.Errorf("From(%v).DefaultIfEmpty(%v)=%v expected %v", test.input, defaultValue, toSlice(q), test.want) | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters