Michael Böiers
12/08/2022, 9:56 AMIterable<T>.takeUntil(pred: (T) -> Boolean)
or else, to make semantics more explicit, let’s add an optional parameter to takeUnless:
list.takeUnless(includeBreakingElement = true) { … }
or how about this:
list.takeUntilIncluding { … }
to that one we could also add an optional parameter indicating what should happen if no element matches. Callers could either want the entire list/stream returned, or an empty list (not possible for streams/sequences).Davio
12/08/2022, 10:58 AMuntil
usually means 'up to but not including' as in the open range (0 until 10) goes to 9.
So you could have takeTo
but that is weird. takeUntil
which I ended up with for lack of a better name also needs to invert the predicate.Michael Böiers
12/08/2022, 10:59 AMDavio
12/08/2022, 11:00 AMDavio
12/08/2022, 11:00 AMRoukanken
12/08/2022, 11:00 AMtakeWhile
& onEach
combo on sequences, but that is uglyJames Richardson
12/08/2022, 11:02 AMDavio
12/08/2022, 11:04 AMMichael Böiers
12/08/2022, 11:20 AMprivate fun <T> Iterable<T>.takeUntilIncluding(p: (T) -> Boolean) = buildList {
for (t in this@takeUntilIncluding) {
add(t)
if (p(t)) break
}
}
Michael Böiers
12/08/2022, 11:22 AMMichael Böiers
12/08/2022, 11:59 AMprivate fun <T> Iterable<T>.dropAfter(p: (T) -> Boolean) = buildList {
for (t in this@dropAfter) {
add(t)
if (p(t)) break
}
}
Davio
12/08/2022, 12:08 PMMichael Böiers
12/08/2022, 12:10 PMprivate fun <T> Iterable<T>.dropAllAfter(p: (T) -> Boolean) = buildList {
for (t in this@dropAllAfter) {
add(t)
if (p(t)) break
}
}
private fun <T> Iterable<T>.takeAllBefore(p: (T) -> Boolean) = buildList {
for (t in this@takeAllBefore) {
if (p(t)) break
add(t)
}
}