-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcommon.go
More file actions
57 lines (49 loc) · 1.65 KB
/
Copy pathcommon.go
File metadata and controls
57 lines (49 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package stdjava
import (
"math"
"golang.org/x/exp/constraints"
)
// Ternary represents Java's ternary operator (condition ? result1 : result2)
func Ternary[T any](condition bool, result1, result2 T) T {
if condition {
return result1
}
return result2
}
// UnsignedRightShift is an implementation of Java's unsigned right shift
// operation where a number is shifted over the number of times specified, but
// the topmost bits are always filled in with zeroes
func UnsignedRightShift[V, A constraints.Integer](value V, amount A) V {
return V(uint32(value) >> amount)
}
// UnsignedRightShiftAssignment represents a right-shift assignment (`>>>=`)
// where a value is assigned the result of an unsigned right shift
func UnsignedRightShiftAssignment[A any, V constraints.Integer](assignTo *A, value V) {
// TODO: Fix this conversion hack, and change the function to take proper values
*assignTo = interface{}(UnsignedRightShift(value, 2)).(A)
}
// HashCode is an implementation of Java's String `hashCode` method
func HashCode(s string) int {
var total int
n := len(s)
for ind, char := range s {
total += int(char) * int(math.Pow(float64(31), float64(n-(ind+1))))
}
return total
}
// MultiDimensionArray constructs an array with two dimensions
func MultiDimensionArray[T any](val []T, dims ...int) [][]T {
arr := make([][]T, dims[0])
for ind := range arr {
arr[ind] = make([]T, dims[1])
}
return arr
}
// MultiDimensionArray3 constructs an array with three dimensions
func MultiDimensionArray3[T any](val [][]T, dims ...int) [][][]T {
arr := make([][][]T, dims[0])
for ind := range arr {
arr[ind] = MultiDimensionArray([]T{}, dims[1:]...)
}
return arr
}