The challenge
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
apples, pears # and bananas
grapes
bananas !apples
The output expected would be:
apples, pears
grapes
bananas
The code would be called like so:
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", charArrayOf('#', '!'))
// result should == "apples, pears\ngrapes\nbananas"
The solution in Kotlin
Option 1:
fun solution(input: String, markers: CharArray): String =
input.lines().map { line ->
line.split(*markers).first().trimEnd()
}.joinToString("\n")
Option 2:
fun solution(input: String, markers: CharArray) =
input.lines().joinToString("\n") { it.takeWhile { !markers.contains(it) }.trim() }
Option 3:
fun solution(input: String, markers: CharArray): String {
return input.lines().map {
val parts = it.split(* markers);
if (parts.size > 1) parts.first().dropLast(1)
else parts.first();
}.joinToString("\n");
}
Test cases to validate our solution
import kotlin.test.assertEquals
import org.junit.Test
class TestExample {
@Test
fun testFixed() {
assertEquals("apples, plums\npears\noranges", solution("apples, plums % and bananas\npears\noranges !applesauce", charArrayOf('%', '!')))
assertEquals("Q\nu\ne", solution("Q @b\nu\ne -e f g", charArrayOf('@', '-')))
}
}