Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Created March 10, 2023 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yongjhih/1014034aacc9c8d6ff03583edb39e8b4 to your computer and use it in GitHub Desktop.
Save yongjhih/1014034aacc9c8d6ff03583edb39e8b4 to your computer and use it in GitHub Desktop.
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