Skip to content

Commit

Permalink
Add list.windows(…)
Browse files Browse the repository at this point in the history
  • Loading branch information
JonasWanke committed Dec 11, 2024
1 parent e536448 commit 61c0afb
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages_v5/example.candy
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,25 @@ fun map[T, R](list: List[T], transform: (T) R) List[R] {
result.append(transform(item))
})
}
fun windows[T](list: List[T], windowLength: Int) List[List[T]] {
# Returns a list over all contiguous windows of length `windowLength`.
#
# The windows overlap. If the `list` is shorter than `windowLength`, the
# resulting list is empty.
needs(windowLength.isPositive())

list.windowsHelper(windowLength, listOf[List[T]]())
}
fun windowsHelper[T](list: List[T], windowLength: Int, resultSoFar: List[List[T]]) List[List[T]] {
let index = resultSoFar.length()
switch index.isLessThanOrEqualTo(list.length().subtract(windowLength)) {
true => list.windowsHelper(
windowLength,
resultSoFar.append(list.getRange(index, index.add(windowLength))),
),
false => resultSoFar,
}
}
impl[T: ToText] List[T]: ToText {
fun toText(self: List[T]) Text {
let items = self.map((item: T) { item.toText() })
Expand Down

0 comments on commit 61c0afb

Please sign in to comment.