Skip to content

Commit

Permalink
Refactored alphanumeric comparator
Browse files Browse the repository at this point in the history
  • Loading branch information
ishubin committed Sep 4, 2015
1 parent fd7bc38 commit 8092f08
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 8 deletions.
Expand Up @@ -31,10 +31,10 @@ public int compare(String left, String right) {
int result;

while(leftReader.hasMore() && rightReader.hasMore()) {
Object leftChunk = parseChunk(leftReader);
Object rightChunk = parseChunk(rightReader);
String leftChunk = parseChunk(leftReader);
String rightChunk = parseChunk(rightReader);

if (leftChunk instanceof Number && rightChunk instanceof Number) {
if (firstLetterIsDigit(leftChunk) && firstLetterIsDigit(rightChunk)) {
result = toInt(leftChunk) - toInt(rightChunk);
if (result != 0) {
return result;
Expand All @@ -50,11 +50,15 @@ public int compare(String left, String right) {
return left.length() - right.length();
}

private Integer toInt(Object chunk) {
return ((Number)chunk).intValue();
private boolean firstLetterIsDigit(String chunk) {
return chunk.length() > 0 && isDigit(chunk.charAt(0));
}

private Object parseChunk(StringCharReader reader) {
private Integer toInt(String chunk) {
return Integer.parseInt(chunk);
}

private String parseChunk(StringCharReader reader) {
if (isDigit(reader.currentSymbol())) {
return parseNumber(reader);
} else {
Expand All @@ -71,13 +75,13 @@ private String parseNonNumber(StringCharReader reader) {
return builder.toString();
}

private Integer parseNumber(StringCharReader reader) {
private String parseNumber(StringCharReader reader) {
StringBuilder builder = new StringBuilder();

while(reader.hasMore() && isDigit(reader.currentSymbol())) {
builder.append(reader.next());
}
return Integer.parseInt(builder.toString());
return builder.toString();
}

private boolean isDigit(char symbol) {
Expand Down
@@ -0,0 +1,40 @@
package com.galenframework.tests.speclang2;

import com.galenframework.speclang2.AlphanumericComparator;
import org.testng.annotations.Test;

import java.util.Collections;
import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class AlphanumericComparatorTest {


@Test
public void shouldSortProperly() {
List<String> list = asList(
"abc 123 edf2",
"abc 123 edf",
"abc 2 edf",
"abc 13 edf",
"abc 12 edf",
"abd 2 edf",
"abb 2 edf"
);

Collections.sort(list, new AlphanumericComparator());

assertThat(list, is(asList(
"abb 2 edf",
"abc 2 edf",
"abc 12 edf",
"abc 13 edf",
"abc 123 edf",
"abc 123 edf2",
"abd 2 edf"
)));
}
}

0 comments on commit 8092f08

Please sign in to comment.