Skip to content

Commit

Permalink
slices: examples for every function!
Browse files Browse the repository at this point in the history
  • Loading branch information
orsinium committed Sep 6, 2023
1 parent 89454c8 commit 1128384
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 2 deletions.
74 changes: 74 additions & 0 deletions slices/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,68 @@ func ExampleTakeRandom() {
// Output: [7 8 5]
}

func ExampleTakeWhile() {
s := []int{3, 5, 7, 8, 9, 10, 11}
odd := func(x int) bool { return x%2 == 1 }
result := slices.TakeWhile(s, odd)
fmt.Println(result)
// Output: [3 5 7]
}

func ExampleToChannel() {
s := []int{3, 4, 5}
ch := slices.ToChannel(s)
result := make([]int, 0)
for x := range ch {
result = append(result, x)
}
fmt.Println(result)
// Output: [3 4 5]
}

func ExampleToKeys() {
s := []int{3, 4, 5}
result := slices.ToKeys(s, 2)
fmt.Println(result)
// Output: map[3:2 4:2 5:2]
}

func ExampleToMap() {
s := []int{3, 4, 5}
result := slices.ToMap(s)
fmt.Println(result)
// Output: map[0:3 1:4 2:5]
}

func ExampleToMapGroupedBy() {
s := []int{3, 4, 5, 13, 23, 14, 25, 34}
lastDigit := func(x int) int { return x % 10 }
result := slices.ToMapGroupedBy(s, lastDigit)
fmt.Println(result)
// Output: map[3:[3 13 23] 4:[4 14 34] 5:[5 25]]
}

func ExampleUniq() {
s := []int{3, 3, 4, 5, 4, 3, 3}
result := slices.Uniq(s)
fmt.Println(result)
// Output: [3 4 5]
}

func ExampleUnique() {
s := []int{3, 4, 5, 3}
result := slices.Unique(s)
fmt.Println(result)
// Output: false
}

func ExampleWindow() {
s := []int{3, 4, 5, 6}
result, _ := slices.Window(s, 2)
fmt.Println(result)
// Output: [[3 4] [4 5] [5 6]]
}

func ExampleWithout() {
s := []int{3, 4, 5, 6, 3, 4, 5, 6, 7, 8}
result := slices.Without(s, 4, 5)
Expand All @@ -592,3 +654,15 @@ func ExampleWrap() {
fmt.Println(result)
// Output: [4]
}

func ExampleZip() {
s1 := []int{3, 4, 5}
s2 := []int{6, 7, 8, 9}
ch := slices.Zip(s1, s2)
result := make([][]int, 0)
for x := range ch {
result = append(result, x)
}
fmt.Println(result)
// Output: [[3 6] [4 7] [5 8]]
}
5 changes: 3 additions & 2 deletions slices/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -636,8 +636,9 @@ func Unique[S ~[]T, T comparable](items S) bool {
return true
}

// Window makes sliding window for a given slice:
// ({1,2,3}, 2) -> (1,2), (2,3)
// Window makes sliding window for the given slice
//
// ({1,2,3}, 2) -> (1,2), (2,3)

Check failure on line 641 in slices/slice.go

View workflow job for this annotation

GitHub Actions / golangci-lint

File is not `gci`-ed with --skip-generated -s standard -s default (gci)
func Window[S ~[]T, T any](items S, size int) ([]S, error) {
if size <= 0 {
return nil, ErrNonPositiveValue
Expand Down

0 comments on commit 1128384

Please sign in to comment.