Skip to content

@andy-gray /LineCountTest.scala
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Line count kata at coding dojo
package linecount
import org.scalatest._
import matchers.ShouldMatchers
class LineCountTest extends FlatSpec with ShouldMatchers {
"the Linecounter" should "think an empty string has zero lines" in {
countLinesIn("") should equal(0)
}
it should "think a string with spaces has zero lines" in {
countLinesIn("") should equal(0)
}
it should "count all the lines with text" in {
countLinesIn(
"""while (true) do durgg();;
|aa;
|ee + 33;}""".stripMargin) should equal(3)
}
it should "ignore empty lines" in {
countLinesIn(
"""while (true) do durgg();
|
|{
| 1 ++
|}
""".stripMargin) should equal(4)
}
it should "ignore inline comments" in {
countLinesIn(
"""while (true) do durgg();
|
|// ignore me
|22 ++ // but not me
|{
| i++
|}
""".stripMargin) should equal(5)
}
it should "ignore block comments" in {
countLinesIn(
"""while (true) do durgg();
|
|/** */
|
|/* comment
|more comment
|end comment *//***///inline
|
|/* don't ignore the command after this */ aCommand(); /* even with this comment after it */ //and this inline one
|{
| i++
|}
""".stripMargin) should equal(5)
}
it should "ignore nested block comments" in {
countLinesIn(
"""while (true) do durgg();
|
| /* comment 1 /* /*
| comment 2
| */
| */
| */ <--
| */
|
|/* comment
|more comment
|end comment *//***///inline
|
|{
| i++
|}
""".stripMargin) should equal(7)
}
it should "correctly count Nigel's first file" in {
countLinesIn(
"""// This file contains 3 lines of code
|public interface Dave {
| /**
|* count the number of lines in a file
|*/
| int countLines(File inFile); // not the real signature!
|}
""".stripMargin) should equal(3)
}
it should "correctly count Nigel's second file" in {
countLinesIn(
"""/*****
|* This is a test program with 5 lines of code
|* \/* no nesting allowed!
|//*****//***/// Slightly pathological comment ending...
|
| public class Hello {
| public static final void main(String [] args) { // gotta love Java
| // Say hello
| System./*wait*/out./*for*/println/*it*/("Hello/*");
| }
|
|}
""".stripMargin) should equal(5)
}
def countLinesIn(text: String): Int = {
val lines = removeBlockComments(text).split("\\n")
lines.filter(notEmptyOrInlineComment).length
}
val notEmptyOrInlineComment: (String => Boolean) = line => {
val trimmedLine = line.trim()
trimmedLine.length > 0 && !trimmedLine.startsWith("//")
}
def removeBlockComments(text: String) = {
val regexForBlockComments = "/\\*(\\n|.)*?\\*/"
text.replaceAll(regexForBlockComments, "")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.