github.com/kaydxh/golang@v0.0.131/go/slices/slices.go (about) 1 /* 2 *Copyright (c) 2022, kaydxh 3 * 4 *Permission is hereby granted, free of charge, to any person obtaining a copy 5 *of this software and associated documentation files (the "Software"), to deal 6 *in the Software without restriction, including without limitation the rights 7 *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 *copies of the Software, and to permit persons to whom the Software is 9 *furnished to do so, subject to the following conditions: 10 * 11 *The above copyright notice and this permission notice shall be included in all 12 *copies or substantial portions of the Software. 13 * 14 *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 *SOFTWARE. 21 */ 22 package slices 23 24 import ( 25 set_ "github.com/kaydxh/golang/go/container/set" 26 "golang.org/x/exp/slices" 27 ) 28 29 func Unique[S ~[]E, E comparable](s S) S { 30 ss := set_.New[E]() 31 for _, v := range s { 32 ss.Insert(v) 33 } 34 35 return ss.List() 36 } 37 38 func SliceIntersection[S ~[]E, E comparable](s1, s2 S) S { 39 ss1 := set_.New[E]() 40 for _, s := range s1 { 41 ss1.Insert(s) 42 } 43 44 ss2 := set_.New[E]() 45 for _, s := range s2 { 46 ss2.Insert(s) 47 } 48 49 var ss S 50 for _, v := range ss1.Intersection(ss2).List() { 51 ss = append(ss, v) 52 } 53 return ss 54 } 55 56 func SliceDifference[S ~[]E, E comparable](s1, s2 S) S { 57 ss1 := set_.New[E]() 58 for _, s := range s1 { 59 ss1.Insert(s) 60 } 61 62 ss2 := set_.New[E]() 63 for _, s := range s2 { 64 ss2.Insert(s) 65 } 66 67 var ss S 68 for _, v := range ss1.Difference(ss2).List() { 69 ss = append(ss, v) 70 } 71 72 return ss 73 } 74 75 func SliceWithCondition[S ~[]E, E comparable](s1 S, cond func(e E) bool) S { 76 ss1 := set_.New[E]() 77 for _, s := range s1 { 78 if cond(s) { 79 ss1.Insert(s) 80 } 81 } 82 83 var ss S 84 for _, v := range ss1.List() { 85 ss = append(ss, v) 86 } 87 88 return ss 89 } 90 91 func FirstOrDefaultZero[S ~[]E, E comparable](s S) E { 92 var zeroE E 93 cond := func(e E) bool { 94 return e != zeroE 95 } 96 i := slices.IndexFunc(s, cond) 97 if i == -1 { 98 return zeroE 99 } 100 return s[i] 101 } 102 103 func RemoveEmpty[S ~[]E, E comparable](s S) S { 104 var ss S 105 var zero E 106 for _, v := range s { 107 if v != zero { 108 ss = append(ss, v) 109 } 110 } 111 112 return ss 113 }