go-hep.org/x/hep@v0.38.1/sliceop/sliceop_example_test.go (about) 1 // Copyright ©2022 The go-hep Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package sliceop_test 6 7 import ( 8 "fmt" 9 10 "go-hep.org/x/hep/sliceop" 11 ) 12 13 // An example of slice filtering 14 func ExampleFilter() { 15 slice := []float64{1, 2, -99, 4, 5, -99, 7} 16 condition := func(x float64) bool { return x > 0 } 17 fmt.Println(sliceop.Filter(nil, slice, condition)) 18 19 // Output: 20 // [1 2 4 5 7] 21 } 22 23 // An example of slice mapping 24 func ExampleMap() { 25 slice := []float64{1, 2, -99, 4, 5, -99, 7} 26 operation := func(x float64) float64 { return x * x } 27 fmt.Println(sliceop.Map(nil, slice, operation)) 28 29 // Output: 30 // [1 4 9801 16 25 9801 49] 31 } 32 33 // An example of slice finding 34 func ExampleFind() { 35 slice := []float64{1, 2, -99, 4, 5, -99, 7} 36 condition := func(x float64) bool { return x == -99 } 37 fmt.Println(sliceop.Find(nil, slice, condition)) 38 39 // Output: 40 // [2 5] 41 } 42 43 // An example of taking a sub-slice defined by indices 44 func ExampleTake() { 45 slice := []float64{1, 2, -99, 4, 5, -99, 7} 46 indices := []int{2, 5} 47 fmt.Println(sliceop.Take(nil, slice, indices)) 48 49 // Output: 50 // [-99 -99] 51 } 52 53 // An example of resizing a slice. 54 func ExampleResize() { 55 slice := []int{1, 2, 3, 4} 56 fmt.Printf("slice: len=%d, cap=%d, vs=%v\n", len(slice), cap(slice), slice) 57 slice = sliceop.Resize(slice, 8) 58 fmt.Printf("slice: len=%d, cap=%d, vs=%v\n", len(slice), cap(slice), slice) 59 slice = sliceop.Resize(slice, 3) 60 fmt.Printf("slice: len=%d, cap=%d, vs=%v\n", len(slice), cap(slice), slice) 61 62 // Output: 63 // slice: len=4, cap=4, vs=[1 2 3 4] 64 // slice: len=8, cap=8, vs=[1 2 3 4 0 0 0 0] 65 // slice: len=3, cap=8, vs=[1 2 3] 66 }