Created
March 10, 2023 11:51
-
-
Save yongjhih/1014034aacc9c8d6ff03583edb39e8b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun CharSequence.indicesOf(pattern: String): Sequence<Int> = sequence { | |
var startIndex = 0 | |
while (true) { | |
startIndex = indexOf(pattern, startIndex) | |
if (startIndex < 0) break | |
yield(startIndex) | |
startIndex += pattern.length | |
} | |
} | |
fun CharSequence.rangesOf(pattern: String): Sequence<IntRange> = | |
indicesOf(pattern).map { it until it + pattern.length } | |
fun CharSequence.rangesOf(patterns: Iterable<String>): Sequence<IntRange> = | |
patterns.flatMapAsSequence { rangesOf(it) } | |
fun CharSequence.withRangesOf(patterns: Iterable<String>): Sequence<Pair<String, IntRange>> = | |
patterns.flatMapAsSequence { pattern -> rangesOf(pattern).map { pattern to it } } | |
fun CharSequence.withTripleRangesOf(patterns: Iterable<String>): Sequence<Triple<String, Int, Int>> = | |
withRangesOf(patterns).map { Triple(it.first, it.second.first, it.second.last) } | |
fun CharSequence.selections(patterns: Iterable<String>): Sequence<Triple<Boolean, CharSequence, IntRange>> = | |
indices.ranges( | |
rangesOf(patterns.sortedByDescending { it.length }) | |
.distinctBy { it.first } | |
.sortedBy { it.first } | |
.asIterable() | |
).map { Triple(it.first, substring(it.second), it.second) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment