github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/isc/take.go (about) 1 package isc 2 3 //Take Returns a list containing first n elements. 4 func Take[T any](list []T, n int) []T { 5 var t []T 6 if n <= 0 { 7 return t 8 } 9 if n >= len(list) { 10 return list 11 } 12 return SubList(list, 0, n) 13 } 14 15 //TakeLast Returns a list containing last n elements. 16 func TakeLast[T any](list []T, n int) []T { 17 var t []T 18 if n <= 0 { 19 return t 20 } 21 if n >= len(list) { 22 return list 23 } 24 return SubList(list, len(list)-n, len(list)) 25 } 26 27 //TakeWhile Returns a list containing first elements satisfying the given predicate. 28 func TakeWhile[T any](list []T, n int, predicate func(T) bool) []T { 29 if n <= 0 { 30 return nil 31 } 32 t := make([]T, n) 33 for i := 0; i < len(list); i++ { 34 if len(t) < n && predicate(list[i]) { 35 t = append(t, list[i]) 36 } 37 } 38 return t 39 } 40 41 //TakeLastWhile Returns a list containing first elements satisfying the given predicate. 42 func TakeLastWhile[T any](list []T, n int, predicate func(T) bool) []T { 43 if n <= 0 { 44 return nil 45 } 46 t := make([]T, n) 47 for i := len(list) - 1; i >= 0; i++ { 48 if len(t) < n && predicate(list[i]) { 49 t = append(t, list[i]) 50 } 51 } 52 return t 53 } 54 55 //Drop Returns a list containing all elements except first [n] elements. 56 func Drop[T any](list []T, n int) []T { 57 if n < 0 { 58 return list 59 } 60 return list[n:] 61 } 62 63 //DropLast Returns a list containing all elements except last n elements 64 func DropLast[T any](list []T, n int) []T { 65 if n < 0 { 66 return nil 67 } 68 if n == 0 { 69 return list 70 } 71 return list[:n] 72 } 73 74 //DropWhile Returns a list containing all elements except first elements that satisfy the given predicate. 75 func DropWhile[T any](list []T, n int, predicate func(T) bool) []T { 76 var t []T 77 var dropCount = 0 78 for i := 0; i < len(list); i++ { 79 if dropCount < n { 80 if predicate(list[i]) { 81 // dropped! 82 dropCount++ 83 } else { 84 t = append(t, list[i]) 85 } 86 } else { 87 t = append(t, list[i]) 88 } 89 } 90 return t 91 } 92 93 //DropLastWhile Returns a list containing all elements except last elements that satisfy the given predicate. 94 func DropLastWhile[T any](list []T, n int, predicate func(T) bool) []T { 95 var t []T 96 var dropCount = 0 97 for i := len(list) - 1; i >= 0; i-- { 98 if dropCount < n { 99 if predicate(list[i]) { 100 // dropped! 101 dropCount++ 102 } else { 103 t = append(t, list[i]) 104 } 105 } else { 106 t = append(t, list[i]) 107 } 108 } 109 // reverse 110 var r []T 111 for i := len(t) - 1; i >= 0; i-- { 112 r = append(r, t[i]) 113 } 114 return t 115 }