You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It would be nice to have a function similar to SQL BETWEEN operator that can filter elements from a Seq that are in some range. This is not an uncommon task when working with statistics, time series, location etc.
We can implement it as an extension for Seq, roughly like this:
Seq(1, 2, 3, 4, 5, 6 ,7, 7, 9, 10).between(4, 7) //will result in Seq(5, 6)
We could also make an extension that would allow filtering sequences of arbitrary product types that don't have an ordering, but have some fields that we can use for comparison, similar to sortBy function, for example:
extension [T](seq: Seq[T])
def betweenBy[U: Ordering](a: U, b: U)(f: T => U): Seq[T] = seq.filter { e =>
Ordering[U].gt(f(e), a) && Ordering[U].lt(f(e), b)
}
locationDataList.betweenBy(hourAgoInstant, Instant.now)(_.timestamp)
IMHO this is much more intuitive, less prone to errors, and nicer to read than using a simple filter function.
P.S. naming is debatable here because I also can suggest using between on numeric types to check if they are in some range, e.g. 1.between(-1, 5) // returns true that would be useful addition too, but might cause confusion if paired with between on Sequences.
The text was updated successfully, but these errors were encountered:
It would be nice to have a function similar to SQL
BETWEEN
operator that can filter elements from aSeq
that are in some range. This is not an uncommon task when working with statistics, time series, location etc.We can implement it as an extension for Seq, roughly like this:
and then use it like so:
We could also make an extension that would allow filtering sequences of arbitrary product types that don't have an ordering, but have some fields that we can use for comparison, similar to
sortBy
function, for example:IMHO this is much more intuitive, less prone to errors, and nicer to read than using a simple filter function.
P.S. naming is debatable here because I also can suggest using
between
on numeric types to check if they are in some range, e.g.1.between(-1, 5) // returns true
that would be useful addition too, but might cause confusion if paired withbetween
on Sequences.The text was updated successfully, but these errors were encountered: