public
Created

Line count kata at coding dojo

  • Download Gist
gistfile1.groovy
Groovy
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 58 59 60 61 62 63 64 65 66
import org.junit.Test
 
class LineCount3 {
@Test void aaa() {
assert countLines("") == 0
assert countLines("""
""") == 0
assert countLines("""
 
int i = 0;
""") == 1
assert countLines("""
int i = 0;
""") == 1
assert countLines("""
// int i = 0;
""") == 0
assert countLines("""
int j = 0; // int i = 0;
""") == 1
assert countLines("""
/* int i = 0; */
""") == 0
assert countLines("""
/* int i = 0;
int j = 0; */
""") == 0
assert countLines("""
/* int i = 0;
int j = 0; */ double d = 0;
""") == 1
}
 
@Test void examples() {
assert countLines(new File("/Users/dima/IdeaProjects/katas/src/main/scala/ru/katas/n13/java_source1.txt").readLines().join("\n")) == 3
assert countLines(new File("/Users/dima/IdeaProjects/katas/src/main/scala/ru/katas/n13/java_source2.txt").readLines().join("\n")) == 5
}
 
private static int countLines(String lines) {
lines = removeMultilineCommentsFrom(lines)
lines = removeSingleLineCommentsFrom(lines)
lines = removeLinesWithOnlyWhitespaces(lines)
lines = collapseSequentialNewLines(lines)
lines = lines.trim()
 
println(lines)
if (!lines.empty) lines.count("\n") + 1
else lines.count("\n")
}
 
public static String removeLinesWithOnlyWhitespaces(String lines) {
lines.replaceAll(/\s+\n/, "\n")
}
 
public static String collapseSequentialNewLines(String lines) {
lines.replaceAll(/\n+/, "\n")
}
 
public static String removeSingleLineCommentsFrom(String lines) {
lines.replaceAll(/\/\/.*/, "")
}
 
public static String removeMultilineCommentsFrom(lines) {
lines.replaceAll(/(?s)\/\*.*?\*\//, "")
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.