├── .github └── workflows │ └── go.yml ├── .gitignore ├── LICENSE ├── README.md ├── funcs ├── functions.go └── functions_test.go ├── go.mod ├── go.sum ├── set ├── set.go └── set_test.go └── slice ├── slice.go └── slice_test.go /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: push 3 | env: 4 | GO111MODULE: on 5 | GOPATH: /home/runner/go 6 | jobs: 7 | build: 8 | runs-on: ubuntu-22.04 9 | name: Go ${{ matrix.go }} 10 | strategy: 11 | matrix: 12 | go: 13 | - '1.18' 14 | - '1.19' 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Setup Go 18 | uses: actions/setup-go@v3 19 | with: 20 | go-version: ${{ matrix.go }} 21 | - run: | 22 | go test -cover -race ./... 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | # Intellij IDE 27 | .idea/ 28 | *.iml 29 | 30 | # test 31 | test_* 32 | 33 | # log 34 | *.log 35 | 36 | vendor/ 37 | 38 | # VS Code 39 | .vscode/ 40 | debug 41 | debug_test 42 | 43 | # Mac 44 | .DS_Store 45 | 46 | # hidden files 47 | .* 48 | _* 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-tools [![Build Status](https://github.com/xgfone/go-tools/actions/workflows/go.yml/badge.svg)](https://github.com/xgfone/go-tools/actions/workflows/go.yml) [![GoDoc](https://pkg.go.dev/badge/github.com/xgfone/go-tools)](https://pkg.go.dev/github.com/xgfone/go-tools/v9) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](https://raw.githubusercontent.com/xgfone/go-tools/master/LICENSE) 2 | 3 | A golang utility tool library supporting `Go1.18+` based on the generics. 4 | 5 | 6 | ## Installation 7 | ```shell 8 | $ go get -u github.com/xgfone/go-tools/v9 9 | ``` 10 | -------------------------------------------------------------------------------- /funcs/functions.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 xgfone 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 funcs provides some useful generic functions. 16 | package funcs 17 | 18 | import ( 19 | "golang.org/x/exp/constraints" 20 | ) 21 | 22 | // Min returns the minimal one between v1 and v2. 23 | func Min[T constraints.Ordered](v1, v2 T) T { 24 | if v1 > v2 { 25 | return v2 26 | } 27 | 28 | return v1 29 | } 30 | 31 | // Max returns the maximum one between v1 and v2. 32 | func Max[T constraints.Ordered](v1, v2 T) T { 33 | if v1 < v2 { 34 | return v2 35 | } 36 | 37 | return v1 38 | } 39 | 40 | // Compare compares v1 and v2, and returns 41 | // 42 | // -1 if v1 < v2 43 | // 0 if v1 == v2 44 | // 1 if v1 > v2 45 | func Compare[T constraints.Ordered](v1, v2 T) int { 46 | if v1 < v2 { 47 | return -1 48 | } else if v1 > v2 { 49 | return 1 50 | } 51 | return 0 52 | } 53 | 54 | // GT reports whether v1 is greater than v2. 55 | func GT[T constraints.Ordered](v1, v2 T) bool { 56 | return Compare(v1, v2) == 1 57 | } 58 | 59 | // GE reports whether v1 is greater than or equal to v2. 60 | func GE[T constraints.Ordered](v1, v2 T) bool { 61 | return Compare(v1, v2) != -1 62 | } 63 | 64 | // LT reports whether v1 is less than v2. 65 | func LT[T constraints.Ordered](v1, v2 T) bool { 66 | return Compare(v1, v2) == -1 67 | } 68 | 69 | // LE reports whether v1 is less than or equal to v2. 70 | func LE[T constraints.Ordered](v1, v2 T) bool { 71 | return Compare(v1, v2) != 1 72 | } 73 | -------------------------------------------------------------------------------- /funcs/functions_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 xgfone 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 funcs 16 | 17 | import "testing" 18 | 19 | func TestMin(t *testing.T) { 20 | if v := Min(1, 2); v != 1 { 21 | t.Errorf("Min: expect %d, but got %d", 1, v) 22 | } 23 | if v := Min(2, 1); v != 1 { 24 | t.Errorf("Min: expect %d, but got %d", 1, v) 25 | } 26 | } 27 | 28 | func TestMax(t *testing.T) { 29 | if v := Max(1, 2); v != 2 { 30 | t.Errorf("Min: expect %d, but got %d", 2, v) 31 | } 32 | if v := Max(2, 1); v != 2 { 33 | t.Errorf("Min: expect %d, but got %d", 2, v) 34 | } 35 | } 36 | 37 | func TestCompare(t *testing.T) { 38 | if v1, v2 := 1, 2; GT(v1, v2) { 39 | t.Errorf("notexpect %d > %d", v1, v2) 40 | } 41 | if v1, v2 := 2, 1; !GT(v1, v2) { 42 | t.Errorf("expect %d > %d", v1, v2) 43 | } 44 | 45 | if v1, v2 := 1, 2; GE(v1, v2) { 46 | t.Errorf("notexpect %d >= %d", v1, v2) 47 | } 48 | if v1, v2 := 2, 1; !GE(v1, v2) { 49 | t.Errorf("expect %d >= %d", v1, v2) 50 | } 51 | if v1, v2 := 2, 2; !GE(v1, v2) { 52 | t.Errorf("expect %d >= %d", v1, v2) 53 | } 54 | 55 | if v1, v2 := 2, 1; LT(v1, v2) { 56 | t.Errorf("notexpect %d < %d", v1, v2) 57 | } 58 | if v1, v2 := 1, 2; !LT(v1, v2) { 59 | t.Errorf("expect %d < %d", v1, v2) 60 | } 61 | 62 | if v1, v2 := 2, 1; LE(v1, v2) { 63 | t.Errorf("notexpect %d <= %d", v1, v2) 64 | } 65 | if v1, v2 := 1, 2; !LE(v1, v2) { 66 | t.Errorf("expect %d <= %d", v1, v2) 67 | } 68 | if v1, v2 := 2, 2; !LE(v1, v2) { 69 | t.Errorf("expect %d <= %d", v1, v2) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/xgfone/go-tools/v9 2 | 3 | require golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f 4 | 5 | go 1.18 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f h1:Al51T6tzvuh3oiwX11vex3QgJ2XTedFPGmbEVh8cdoc= 2 | golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= 3 | -------------------------------------------------------------------------------- /set/set.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 xgfone 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 set provides a common set based on generics. 16 | package set 17 | 18 | import ( 19 | "bytes" 20 | "fmt" 21 | ) 22 | 23 | // Set is a set type. 24 | type Set[T comparable] struct { 25 | cache map[T]struct{} 26 | } 27 | 28 | // NewSet returns a new Set from a slice. 29 | func NewSet[T comparable](elements ...T) Set[T] { 30 | s := Set[T]{cache: make(map[T]struct{}, len(elements))} 31 | s.Add(elements...) 32 | return s 33 | } 34 | 35 | // NewSetWithCap returns a new Set with the initialization capacity. 36 | func NewSetWithCap[T comparable](cap int) Set[T] { 37 | return Set[T]{cache: make(map[T]struct{}, cap)} 38 | } 39 | 40 | // NewSetFromSet returns a new Set. 41 | func NewSetFromSet[T comparable](sets ...Set[T]) Set[T] { 42 | s := Set[T]{cache: make(map[T]struct{}, len(sets))} 43 | s.UnionUpdate(sets...) 44 | return s 45 | } 46 | 47 | func (s Set[T]) String() string { 48 | var i int 49 | buf := bytes.NewBuffer(nil) 50 | buf.Grow(128) 51 | buf.WriteByte('{') 52 | for key := range s.cache { 53 | if i == 0 { 54 | fmt.Fprintf(buf, "%v", key) 55 | } else { 56 | fmt.Fprintf(buf, " %v", key) 57 | } 58 | i++ 59 | } 60 | buf.WriteByte('}') 61 | return buf.String() 62 | } 63 | 64 | // Add adds some elements into the set. 65 | func (s Set[T]) Add(elements ...T) { 66 | for _, v := range elements { 67 | s.cache[v] = struct{}{} 68 | } 69 | } 70 | 71 | // Remove removes the elements from the set. 72 | func (s Set[T]) Remove(elements ...T) { 73 | for _, v := range elements { 74 | delete(s.cache, v) 75 | } 76 | } 77 | 78 | // Pop removes and returns an arbitrary element from the set. 79 | func (s Set[T]) Pop() (element T, ok bool) { 80 | for e := range s.cache { 81 | delete(s.cache, e) 82 | return e, true 83 | } 84 | return 85 | } 86 | 87 | // Clear removes all the elements from the set. 88 | func (s Set[T]) Clear() { 89 | for key := range s.cache { 90 | delete(s.cache, key) 91 | } 92 | } 93 | 94 | // Contains returns true if the element is in the set. Or return false. 95 | func (s Set[T]) Contains(element T) bool { 96 | _, ok := s.cache[element] 97 | return ok 98 | } 99 | 100 | // Equal returns true if s == other. 101 | func (s Set[T]) Equal(other Set[T]) bool { 102 | for e := range s.cache { 103 | if !other.Contains(e) { 104 | return false 105 | } 106 | } 107 | 108 | for e := range other.cache { 109 | if !s.Contains(e) { 110 | return false 111 | } 112 | } 113 | 114 | return true 115 | } 116 | 117 | // Size returns the number of the elements in the set. 118 | func (s Set[T]) Size() int { 119 | return len(s.cache) 120 | } 121 | 122 | // Slice converts the set to a slice. 123 | func (s Set[T]) Slice() []T { 124 | list := make([]T, 0, len(s.cache)) 125 | for e := range s.cache { 126 | list = append(list, e) 127 | } 128 | return list 129 | } 130 | 131 | // Clone returns a copy of the current set. 132 | func (s Set[T]) Clone() Set[T] { 133 | cs := Set[T]{cache: make(map[T]struct{}, len(s.cache))} 134 | for e := range s.cache { 135 | cs.cache[e] = struct{}{} 136 | } 137 | return cs 138 | } 139 | 140 | // Range travels all the elements of the set. 141 | func (s Set[T]) Range(f func(element T)) { 142 | for e := range s.cache { 143 | f(e) 144 | } 145 | } 146 | 147 | ////////////////////////////////////////////////////////////////////////////// 148 | 149 | // UnionUpdate updates the set, adding the elements from all others. 150 | func (s Set[T]) UnionUpdate(others ...Set[T]) { 151 | for _, set := range others { 152 | for e := range set.cache { 153 | s.cache[e] = struct{}{} 154 | } 155 | } 156 | } 157 | 158 | // DifferenceUpdate updates the set, removing the elements found in others. 159 | func (s Set[T]) DifferenceUpdate(others ...Set[T]) { 160 | for _, set := range others { 161 | for e := range set.cache { 162 | delete(s.cache, e) 163 | } 164 | } 165 | } 166 | 167 | // IntersectionUpdate updates the set, keeping only elements found in it and all others. 168 | func (s Set[T]) IntersectionUpdate(others ...Set[T]) { 169 | cache := make(map[T]struct{}) 170 | for e := range s.cache { 171 | var no bool 172 | for _, set := range others { 173 | if !set.Contains(e) { 174 | no = true 175 | break 176 | } 177 | } 178 | if !no { 179 | cache[e] = struct{}{} 180 | } 181 | } 182 | s.cache = cache 183 | } 184 | 185 | // SymmetricDifferenceUpdate updates the set, keeping only elements 186 | // found in either set, but not in both. 187 | func (s Set[T]) SymmetricDifferenceUpdate(other Set[T]) { 188 | cache := make(map[T]struct{}) 189 | 190 | for e := range other.cache { 191 | if _, ok := s.cache[e]; !ok { 192 | cache[e] = struct{}{} 193 | } 194 | } 195 | 196 | for e := range s.cache { 197 | if _, ok := other.cache[e]; !ok { 198 | cache[e] = struct{}{} 199 | } 200 | } 201 | 202 | s.cache = cache 203 | } 204 | 205 | ////////////////////////////////////////////////////////////////////////////// 206 | 207 | // Union returns a new set with elements from the set and all others. 208 | func (s Set[T]) Union(others ...Set[T]) Set[T] { 209 | r := s.Clone() 210 | for _, set := range others { 211 | for e := range set.cache { 212 | r.cache[e] = struct{}{} 213 | } 214 | } 215 | return r 216 | } 217 | 218 | // Difference returns a new set with elements in the set that are not in the others. 219 | func (s Set[T]) Difference(others ...Set[T]) Set[T] { 220 | r := s.Clone() 221 | for _, set := range others { 222 | for e := range set.cache { 223 | delete(r.cache, e) 224 | } 225 | } 226 | return r 227 | } 228 | 229 | // Intersection returns a new set with elements common to the set and all others. 230 | func (s Set[T]) Intersection(others ...Set[T]) Set[T] { 231 | r := NewSet[T]() 232 | for e := range s.cache { 233 | var no bool 234 | for _, set := range others { 235 | if !set.Contains(e) { 236 | no = true 237 | break 238 | } 239 | } 240 | if !no { 241 | r.cache[e] = struct{}{} 242 | } 243 | } 244 | return r 245 | } 246 | 247 | // SymmetricDifference returns a new set with elements in either the set 248 | // or other but not both. 249 | func (s Set[T]) SymmetricDifference(other Set[T]) Set[T] { 250 | r := NewSet[T]() 251 | 252 | for e := range other.cache { 253 | if _, ok := s.cache[e]; !ok { 254 | r.cache[e] = struct{}{} 255 | } 256 | } 257 | 258 | for e := range s.cache { 259 | if _, ok := other.cache[e]; !ok { 260 | r.cache[e] = struct{}{} 261 | } 262 | } 263 | 264 | return r 265 | } 266 | -------------------------------------------------------------------------------- /set/set_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 xgfone 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 set 16 | 17 | import ( 18 | "fmt" 19 | ) 20 | 21 | func ExampleSet() { 22 | intset1 := NewSet(1, 2, 3) 23 | intset2 := NewSet(7, 8, 9) 24 | strset := NewSet("a", "b", "c") 25 | 26 | intset1.Add(3, 4, 5) 27 | strset.Add("c", "d", "e") 28 | fmt.Println(intset1.Size(), strset.Size()) 29 | fmt.Println(intset1.Contains(4), intset1.Contains(5), intset1.Contains(6)) 30 | fmt.Println(strset.Contains("d"), strset.Contains("e"), strset.Contains("z")) 31 | // 5 5 32 | // true true false 33 | // true true false 34 | 35 | intset1.Remove(1, 2, 9) 36 | strset.Remove("a", "b", "z") 37 | fmt.Println(intset1.Size(), strset.Size()) 38 | fmt.Println(intset1.Contains(1), intset1.Contains(2)) 39 | fmt.Println(strset.Contains("a"), strset.Contains("b")) 40 | // 3 3 41 | // false false 42 | // false false 43 | 44 | list1 := intset1.Slice() 45 | fmt.Println(list1[0]) 46 | fmt.Println(list1[1]) 47 | fmt.Println(list1[2]) 48 | // 3 49 | // 4 50 | // 5 51 | 52 | list2 := strset.Slice() 53 | fmt.Println(list2[0]) 54 | fmt.Println(list2[1]) 55 | fmt.Println(list2[2]) 56 | // c 57 | // d 58 | // e 59 | 60 | union := intset1.Union(intset2) 61 | diff := intset1.Difference(intset2) 62 | inter := intset1.Intersection(intset2) 63 | sdiff := intset1.SymmetricDifference(intset2) 64 | fmt.Println(union.Size(), diff.Size(), inter.Size(), sdiff.Size()) 65 | // 6 3 0 6 66 | 67 | fmt.Println(union.Difference(intset1).Equal(intset2)) 68 | fmt.Println(union.Equal(sdiff)) 69 | // true 70 | // true 71 | 72 | union.Range(func(element int) { 73 | fmt.Println(element) 74 | }) 75 | for _, v := range union.Slice() { 76 | fmt.Println(v) 77 | } 78 | // 3 79 | // 4 80 | // 5 81 | // 7 82 | // 8 83 | // 9 84 | 85 | // Unordered output: 86 | // 5 5 87 | // true true false 88 | // true true false 89 | // 3 3 90 | // false false 91 | // false false 92 | // 3 93 | // 4 94 | // 5 95 | // c 96 | // d 97 | // e 98 | // 6 3 0 6 99 | // true 100 | // true 101 | // 3 102 | // 4 103 | // 5 104 | // 7 105 | // 8 106 | // 9 107 | // 3 108 | // 4 109 | // 5 110 | // 7 111 | // 8 112 | // 9 113 | } 114 | -------------------------------------------------------------------------------- /slice/slice.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 xgfone 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 provides some assistant functions about slice. 16 | package slice 17 | 18 | // Reverse reverses the elements in the slice. 19 | func Reverse[E any](vs []E) { 20 | _len := len(vs) - 1 21 | if _len <= 0 { 22 | return 23 | } 24 | 25 | for i, j := 0, _len/2; i <= j; i++ { 26 | k := _len - i 27 | vs[i], vs[k] = vs[k], vs[i] 28 | } 29 | } 30 | 31 | // Contains reports whether vs contains v. 32 | func Contains[E comparable](vs []E, v E) bool { 33 | for i, _len := 0, len(vs); i < _len; i++ { 34 | if vs[i] == v { 35 | return true 36 | } 37 | } 38 | return false 39 | } 40 | 41 | // ToInterfaces converts []any to []interface{}. 42 | func ToInterfaces[T any](vs []T) []interface{} { 43 | is := make([]interface{}, len(vs)) 44 | for i, _len := 0, len(vs); i < _len; i++ { 45 | is[i] = vs[i] 46 | } 47 | return is 48 | } 49 | -------------------------------------------------------------------------------- /slice/slice_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 xgfone 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 16 | 17 | import "fmt" 18 | 19 | func ExampleContains() { 20 | fmt.Println(Contains([]int{1, 2, 3}, 0)) 21 | fmt.Println(Contains([]int{1, 2, 3}, 1)) 22 | fmt.Println(Contains([]int{1, 2, 3}, 2)) 23 | fmt.Println(Contains([]int{1, 2, 3}, 3)) 24 | fmt.Println(Contains([]int{1, 2, 3}, 4)) 25 | 26 | // Output: 27 | // false 28 | // true 29 | // true 30 | // true 31 | // false 32 | } 33 | 34 | func ExampleReverse() { 35 | vs1 := []string{"a", "b", "c", "d"} 36 | Reverse(vs1) 37 | fmt.Println(vs1) 38 | 39 | vs2 := []int{1, 2, 3, 4} 40 | Reverse(vs2) 41 | fmt.Println(vs2) 42 | 43 | // Output: 44 | // [d c b a] 45 | // [4 3 2 1] 46 | } 47 | 48 | func ExampleToInterfaces() { 49 | ss := []string{"a", "b", "c"} 50 | vs1 := ToInterfaces(ss) 51 | fmt.Printf("%T: %v\n", vs1, vs1) 52 | 53 | ints := []int{1, 2, 3} 54 | vs2 := ToInterfaces(ints) 55 | fmt.Printf("%T: %v\n", vs2, vs2) 56 | 57 | // Output: 58 | // []interface {}: [a b c] 59 | // []interface {}: [1 2 3] 60 | } 61 | --------------------------------------------------------------------------------