Sliding / Sliding Window, a Scala language concept

Last updated

Get fixed-length sliding sub-sequences (sliding windows) from another sequence

assert(List.empty.sliding(2).toList == List.empty)

assert(List(1).sliding(2).toList == List(List(1)))

assert(List(1, 2).sliding(2).toList == List(List(1, 2)))

assert(List(1, 2, 3).sliding(2).toList == List(List(1, 2), List(2, 3)))

assert(
  List(1, 2, 3, 4).sliding(2).toList ==
    List(List(1, 2), List(2, 3), List(3, 4))
)

Note that if the length of the input list is less than the sliding window, then the whole input list will be returned)

For Iterators

It even works on Iterators:

assert(Iterator.empty.sliding(2).toList == List())

assert(Iterator(1).sliding(2).toList == List(Seq(1)))

assert(Iterator(1, 2).sliding(2).toList == List(Seq(1, 2)))

assert(Iterator(1, 2, 3).sliding(2).toList == List(Seq(1, 2), Seq(2, 3)))