Skip to content

Commit

Permalink
Update minibox to load simple fractions (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
jessicasyu authored Oct 20, 2023
1 parent 661f527 commit 9e7d147
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/arcade/core/util/MiniBox.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ public int getInt(String id) {
*/
public double getDouble(String id) {
String s = contents.get(id);

if (s != null && s.contains("/")) {
String[] split = s.split("/", 2);
double numerator = (!split[0].matches(NUMBER_REGEX)
? Double.NaN
: Double.parseDouble(split[0]));
double denominator = (!split[1].matches(NUMBER_REGEX)
? Double.NaN
: Double.parseDouble(split[1]));
return (denominator == 0 ? Double.NaN : numerator / denominator);
}

return (s == null || !s.matches(NUMBER_REGEX) ? Double.NaN : Double.parseDouble(s));
}

Expand Down
32 changes: 32 additions & 0 deletions test/arcade/core/util/MiniBoxTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,38 @@ public void getDouble_givenValidKeyGivenDouble_returnsValue() {
}
}

@Test
public void getDouble_givenValidKeyGivenValidFraction_returnsValue() {
String key = randomString();
String[] doubles = new String[] { "1/2", "3/4", "5E-1/10" };
double[] values = new double[] { 0.5, 0.75, 0.05 };
for (int i = 0; i < doubles.length; i++) {
MiniBox box = new MiniBox();
box.put(key, doubles[i]);
assertEquals(values[i], box.getDouble(key), EPSILON);
}
}

@Test
public void getDouble_givenValidKeyGivenInvalidFraction_returnsNaN() {
String key = randomString();
String[] doubles = new String[] { "1/2/3", "/1", "1/" };
for (int i = 0; i < doubles.length; i++) {
MiniBox box = new MiniBox();
box.put(key, doubles[i]);
assertTrue(Double.isNaN(box.getDouble(key)));
}
}

@Test
public void getDouble_givenValidKeyGivenZeroFraction_returnsNaN() {
MiniBox box = new MiniBox();
String key = randomString();
String contents = "1/0";
box.put(key, contents);
assertTrue(Double.isNaN(box.getDouble(key)));
}

@Test
public void getDouble_givenInvalidContentsGivenString_returnsNaN() {
MiniBox box = new MiniBox();
Expand Down

0 comments on commit 9e7d147

Please sign in to comment.