Chachako
09/07/2021, 9:11 AMremoveSuffix
or removePrefix
?Chachako
09/07/2021, 9:24 AMfun <T> List<T>.endsWith(vararg slice: T) = this.toList().takeLast(slice.size) == slice.toList()
fun <T> List<T>.removeSuffix(vararg suffix: T) =
if (endsWith(*suffix)) this.dropLast(suffix.size) else this
I hope this can help others.ephemient
09/07/2021, 9:45 AMfun <T> Sequence<T>.removeSuffix(vararg slice: T): Sequence<T> {
require(slice.isNotEmpty())
return sequence {
val iter = this@removeSuffix.windowed(slice.size).iterator()
if (!iter.hasNext()) return@sequence
while (true) {
val window = iter.next()
if (iter.hasNext()) {
yield(window.first())
} else {
if (window != slice.asList()) yieldAll(window)
break
}
}
}
}
Chachako
09/07/2021, 9:47 AMwindowed
operator I have not touched yet, I will go see! Very interestingephemient
09/07/2021, 9:59 AMJoffrey
09/07/2021, 10:13 AMthis.toList()
before calling takeLast()
though? It's already a list, and creating a new instance doesn't seem to serve any purpose hereKlitos Kyriacou
09/07/2021, 10:49 AMrequire(slice.isNotEmpty())
shouldn't be needed, as "xyz".endsWith("")
is allowed (returns true).Chachako
09/07/2021, 10:57 AMephemient
09/07/2021, 4:01 PM.windowed(0)
is nonsense. that case should probably be handled separately.