Merge pull request #314 from mhshams/upstream

KT-4139 FIXED
This commit is contained in:
max-kammerer
2013-10-29 00:57:14 -07:00
2 changed files with 48 additions and 0 deletions
+16
View File
@@ -332,6 +332,22 @@ public inline fun String.partition(predicate: (Char) -> Boolean): Pair<String, S
return Pair(first.toString(), second.toString())
}
/**
* Returns a new List containing the results of applying the given *transform* function to each character in this string
*
*/
public inline fun <R> String.map(transform: (Char) -> R): List<R> = mapTo(ArrayList<R>(), transform)
/**
* Transforms each character of this string with the given *transform* function and
* adds each return value to the given *result* collection
*
*/
public inline fun <R, C: MutableCollection<in R>> String.mapTo(result: C, transform: (Char) -> R): C {
for (c in this) result.add(transform(c))
return result
}
/**
* Returns the result of transforming each character to one or more values which are concatenated together into a single list
*
+32
View File
@@ -142,6 +142,38 @@ class StringJVMTest {
assertEquals("abc", pair.second, "pair.second")
}
test fun map() {
assertEquals(arrayListOf('a', 'b', 'c'), "abc".map({ it }))
assertEquals(arrayListOf(true, false, true), "AbC".map({ it.isUpperCase() }))
assertEquals(arrayListOf<Boolean>(), "".map({ it.isUpperCase() }))
assertEquals(arrayListOf(97, 98, 99), "abc".map({ it.toInt() }))
}
test fun mapTo() {
val result1 = arrayListOf<Char>()
val return1 = "abc".mapTo(result1, { it })
assertEquals(result1, return1)
assertEquals(arrayListOf('a', 'b', 'c'), result1)
val result2 = arrayListOf<Boolean>()
val return2 = "AbC".mapTo(result2, { it.isUpperCase() })
assertEquals(result2, return2)
assertEquals(arrayListOf(true, false, true), result2)
val result3 = arrayListOf<Boolean>()
val return3 = "".mapTo(result3, { it.isUpperCase() })
assertEquals(result3, return3)
assertEquals(arrayListOf<Boolean>(), result3)
val result4 = arrayListOf<Int>()
val return4 = "abc".mapTo(result4, { it.toInt() })
assertEquals(result4, return4)
assertEquals(arrayListOf(97, 98, 99), result4)
}
test fun flatMap() {
val data = "abcd"
val result = data.flatMap { listOf(it) }