Skip to content
This repository was archived by the owner on Dec 28, 2024. It is now read-only.

Commit e523fd8

Browse files
committed
Add Matrix::GetOrDefault and type BoolMatrix
1 parent 607e2ae commit e523fd8

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

common/util/matrix.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ type UInt32Matrix = Matrix[uint32]
2424
type UInt64Matrix = Matrix[uint64]
2525

2626
type CharMatrix = UInt8Matrix
27+
type BoolMatrix = Matrix[bool]
2728

2829
func NewMatrixFromRows[T any](
2930
matrix [][]T,
@@ -77,3 +78,15 @@ func (m Matrix[T]) Get(
7778
}
7879
return m.matrix[y][x], nil
7980
}
81+
82+
func (m Matrix[T]) GetOrDefault(
83+
x int,
84+
y int,
85+
defaultReturn T,
86+
) (T, error) {
87+
v, err := m.Get(x, y)
88+
if err != nil {
89+
return defaultReturn, err
90+
}
91+
return v, nil
92+
}

common/util/matrix_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,33 @@ func TestMatrix_Get(t *testing.T) {
185185
}
186186
}
187187
}
188+
189+
func TestMatrix_GetOrDefault(t *testing.T) {
190+
defaultValue := Coordinate{1337, 420}
191+
192+
for x := -1; x <= matrix.MaxX+1; x++ {
193+
for y := -1; y <= matrix.MaxY+1; y++ {
194+
expected := Coordinate{X: x, Y: y}
195+
actual, err := matrix.GetOrDefault(x, y, defaultValue)
196+
isIn := matrix.IsInMatrix(x, y)
197+
198+
if isIn {
199+
if actual != expected {
200+
t.Errorf("Expected %v, but was %v", expected, actual)
201+
}
202+
203+
if err != nil {
204+
t.Errorf("Expected an error, but got nil")
205+
}
206+
} else {
207+
if actual != defaultValue {
208+
t.Errorf("Expected default value fallback (%v), but got %v", defaultValue, actual)
209+
}
210+
211+
if err == nil {
212+
t.Errorf("Expected err to be nil, but was %v", err)
213+
}
214+
}
215+
}
216+
}
217+
}

0 commit comments

Comments
 (0)