Skip to content

Commit 1220833

Browse files
committed
Add Array::windows
1 parent 36ee646 commit 1220833

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

builtin/array.mbt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,6 +1639,45 @@ pub fn Array::chunk_by[T](
16391639
chunks
16401640
}
16411641
1642+
///|
1643+
/// Generates overlapping subslices (sliding windows) of the specified size.
1644+
///
1645+
/// Parameters:
1646+
///
1647+
/// * `array` : The array to be processed with sliding windows.
1648+
/// * `size` : The window length. Must be a positive integer.
1649+
///
1650+
/// Returns an array of slices, where each inner slice is a contiguous subslice
1651+
/// of the original array. Windows are produced with a step size of 1. If the
1652+
/// original array's length is less than the specified window size, the result
1653+
/// will be an empty array.
1654+
///
1655+
/// Example:
1656+
///
1657+
/// ```moonbit
1658+
/// test "windows" {
1659+
/// let arr = [1, 2, 3, 4, 5]
1660+
/// let windows = arr.windows(2)
1661+
/// inspect!(windows, content="[[1, 2], [2, 3], [3, 4], [4, 5]]")
1662+
/// }
1663+
///
1664+
/// test "empty_windows" {
1665+
/// let arr : Array[Int] = [1, 2]
1666+
/// inspect!(arr.windows(3), content="[]")
1667+
/// }
1668+
/// ```
1669+
pub fn Array::windows[T](self : Array[T], size : Int) -> Array[ArrayView[T]] {
1670+
let len = self.length() - size + 1
1671+
if len < 1 {
1672+
return []
1673+
}
1674+
let windows = Array::new(capacity=len)
1675+
for i in 0..<len {
1676+
windows.push(self[i:i + size])
1677+
}
1678+
windows
1679+
}
1680+
16421681
///|
16431682
/// Splits an array into chunks using a predicate function. Creates chunks by
16441683
/// grouping consecutive elements that do not satisfy the predicate function.

builtin/array_test.mbt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,17 @@ test "chunks_by" {
494494
)
495495
}
496496

497+
///|
498+
test "array_windows" {
499+
let arr = [1, 2, 3, 4, 5, 6]
500+
let windows = arr.windows(11)
501+
inspect!(windows, content="[]")
502+
let windows = arr.windows(5)
503+
inspect!(windows, content="[[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]")
504+
let windows = arr.windows(1)
505+
inspect!(windows, content="[[1], [2], [3], [4], [5], [6]]")
506+
}
507+
497508
///|
498509
test "array_get_out_of_bounds" {
499510
let arr = [1, 2, 3]

builtin/builtin.mbti

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ impl Array {
124124
unsafe_blit_fixed[A](Self[A], Int, FixedArray[A], Int, Int) -> Unit
125125
unsafe_get[T](Self[T], Int) -> T
126126
unsafe_pop[T](Self[T]) -> T
127+
windows[T](Self[T], Int) -> Self[ArrayView[T]]
127128
}
128129
impl[T] Add for Array[T]
129130
impl[T : Compare] Compare for Array[T]

0 commit comments

Comments
 (0)