Skip to content

Commit 9b43f0e

Browse files
committed
feat: slice xor
1 parent 41f82ac commit 9b43f0e

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

slice/xor.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package slice
2+
3+
// Xor Creates an array of unique values. The order of result values is determined by the order they occur in the arrays.
4+
func Xor[T comparable](arrays ...[]T) (result []T) {
5+
if len(arrays) < 2 {
6+
return
7+
}
8+
result = arrays[0]
9+
for i := 1; i < len(arrays); i++ {
10+
result = xor(result, arrays[i])
11+
if len(result) == 0 {
12+
break
13+
}
14+
}
15+
return
16+
}
17+
18+
func xor[T comparable](arr1 []T, arr2 []T) (result []T) {
19+
result = make([]T, 0)
20+
for i := 0; i < len(arr1); i++ {
21+
if IndexOf(arr2, arr1[i], 0) < 0 {
22+
result = append(result, arr1[i])
23+
}
24+
}
25+
return
26+
}

slice/xor_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package slice
2+
3+
import "fmt"
4+
5+
func ExampleXor() {
6+
arr1 := []string{"one", "two", ",", ".", "!", "ok"}
7+
arr2 := []string{"two", ".", "one", "hello", "123"}
8+
9+
arr3 := []string{"one", ".", ",", "!", "kk", "09"}
10+
11+
fmt.Println(Xor(arr1))
12+
fmt.Println(Xor(arr1, arr2))
13+
fmt.Println(Xor(arr1, arr2, arr3))
14+
//Output:
15+
//[]
16+
//[, ! ok]
17+
//[ok]
18+
}

0 commit comments

Comments
 (0)