Add .get method for coordinate element retrieval to grid
Coordinates passed in access the correct index in the internal list.
This commit is contained in:
parent
46b11bc33b
commit
6c3fcbe7b0
2 changed files with 24 additions and 5 deletions
|
@ -21,10 +21,10 @@ class Grid<E> extends DelegatingList<E> {
|
||||||
height = h,
|
height = h,
|
||||||
super(l);
|
super(l);
|
||||||
|
|
||||||
E elementAtPos(int x, int y) {
|
E get(int x, int y) {
|
||||||
int i = toIndex(x, y);
|
int i = toIndex(x, y);
|
||||||
if (i >= length) throw RangeError.index(i, this);
|
if (i >= length || x > width - 1) throw RangeError.index(i, this);
|
||||||
_internal[i];
|
return _internal[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
void setElement(int x, int y, E value) {
|
void setElement(int x, int y, E value) {
|
||||||
|
@ -33,8 +33,6 @@ class Grid<E> extends DelegatingList<E> {
|
||||||
_internal[i] = value;
|
_internal[i] = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
E get(int x, int y) => elementAtPos(x, y);
|
|
||||||
|
|
||||||
void set(int x, int y, E value) => setElement(x, y, value);
|
void set(int x, int y, E value) => setElement(x, y, value);
|
||||||
|
|
||||||
/// Calculate list index from coordinates.
|
/// Calculate list index from coordinates.
|
||||||
|
|
|
@ -92,6 +92,27 @@ void main() {
|
||||||
expect(sut.toIndex(1, 1), equals(4));
|
expect(sut.toIndex(1, 1), equals(4));
|
||||||
}, tags: const ["happy"]);
|
}, tags: const ["happy"]);
|
||||||
});
|
});
|
||||||
|
group("coordinates getter", () {
|
||||||
|
Grid sut;
|
||||||
|
setUp(() {
|
||||||
|
sut = Grid(3, 3);
|
||||||
|
sut.setAll(0,
|
||||||
|
["Hey", "you", "me", "together", "Hello", null, "I", "am", "ready."]);
|
||||||
});
|
});
|
||||||
|
test("returns null if no element exists at the position requested", () {
|
||||||
|
expect(sut.get(2, 1), null);
|
||||||
|
}, tags: const ["sad"]);
|
||||||
|
test("throws RangeError if requesting element outside of grid width", () {
|
||||||
|
expect(() => sut.get(4, 1), throwsRangeError);
|
||||||
|
}, tags: const ["bad"]);
|
||||||
|
test("throws RangeError if requesting element outside of grid height", () {
|
||||||
|
expect(() => sut.get(1, 4), throwsRangeError);
|
||||||
|
}, tags: const ["bad"]);
|
||||||
|
test("returns element at correct index", () {
|
||||||
|
expect(sut.get(1, 0), "you");
|
||||||
|
}, tags: const ["happy"]);
|
||||||
|
test("returns last element correctly", () {
|
||||||
|
expect(sut.get(2, 2), "ready.");
|
||||||
|
}, tags: const ["happy"]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue