|
| 1 | +// Copyright 2023 the go-functional authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package slice_test |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + |
| 20 | + "github.com/mikehelmick/go-functional/slice" |
| 21 | +) |
| 22 | + |
| 23 | +func ExampleFilter() { |
| 24 | + type Account struct { |
| 25 | + Name string |
| 26 | + Writer bool |
| 27 | + } |
| 28 | + |
| 29 | + input := []*Account{ |
| 30 | + { |
| 31 | + Name: "Bob", |
| 32 | + Writer: false, |
| 33 | + }, |
| 34 | + { |
| 35 | + Name: "Alice", |
| 36 | + Writer: true, |
| 37 | + }, |
| 38 | + { |
| 39 | + Name: "Steve", |
| 40 | + Writer: false, |
| 41 | + }, |
| 42 | + } |
| 43 | + |
| 44 | + // Function to check if an element is even |
| 45 | + isWriter := func(x *Account) bool { |
| 46 | + return x.Writer |
| 47 | + } |
| 48 | + |
| 49 | + writers := slice.Filter(input, isWriter) |
| 50 | + fmt.Printf("Writers:\n") |
| 51 | + for _, writer := range writers { |
| 52 | + fmt.Printf(" - name: %v\n", writer.Name) |
| 53 | + } |
| 54 | + |
| 55 | + isReadOnly := func(x *Account) bool { |
| 56 | + return !x.Writer |
| 57 | + } |
| 58 | + |
| 59 | + readers := slice.Filter(input, isReadOnly) |
| 60 | + fmt.Printf("Readers:\n") |
| 61 | + for _, reader := range readers { |
| 62 | + fmt.Printf(" - name: %v\n", reader.Name) |
| 63 | + } |
| 64 | + |
| 65 | + // Output: |
| 66 | + // Writers: |
| 67 | + // - name: Alice |
| 68 | + // Readers: |
| 69 | + // - name: Bob |
| 70 | + // - name: Steve |
| 71 | +} |
0 commit comments