Imperative trim implementation to prevent double lambda expansion in inline function.

This commit is contained in:
Ilya Gorbunov
2015-03-20 17:44:44 +03:00
parent 5b2a5c78ca
commit 0484d3bf2f
+23 -7
View File
@@ -10,13 +10,29 @@ public fun String.trim(prefix: String, postfix: String): String = trimLeading(pr
* Returns the string with leading and trailing characters matching the [predicate] trimmed. * Returns the string with leading and trailing characters matching the [predicate] trimmed.
*/ */
inline public fun String.trim(predicate: (Char) -> Boolean): String { inline public fun String.trim(predicate: (Char) -> Boolean): String {
val indices = this.indices var startIndex = 0
for (startIndex in indices) var endIndex = length() - 1
if (!predicate(this[startIndex])) var startFound = false
for (endIndex in indices.reversed())
if (!predicate(this[endIndex])) while (startIndex <= endIndex) {
return substring(startIndex, endIndex + 1) val index = if (!startFound) startIndex else endIndex
return "" val match = predicate(this[index])
if (!startFound) {
if (!match)
startFound = true
else
startIndex += 1
}
else {
if (!match)
break
else
endIndex -= 1
}
}
return substring(startIndex, endIndex + 1)
} }
/** /**