Skip to content

Instantly share code, notes, and snippets.

@kakajika
Last active March 27, 2018 10:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakajika/dfcdafe835dd38a99c45a138faa23b11 to your computer and use it in GitHub Desktop.
Save kakajika/dfcdafe835dd38a99c45a138faa23b11 to your computer and use it in GitHub Desktop.
Ported from Kotlin-stdlib
import Foundation
extension Array {
func windowed(size: Int, step: Int = 1, partialWindows: Bool = false) -> [[Element]] {
let count = self.count
var index = 0
var result: [[Element]] = []
while (index < count) {
let windowSize = Swift.min(size, count - index)
if windowSize < size && !partialWindows {
break
}
result.append(Array(self[index ..< (index + windowSize)]))
index += step
}
return result
}
func chunked(size: Int, partialWindows: Bool = false) -> [[Element]] {
return self.windowed(size: size, step: size, partialWindows: partialWindows)
}
}
print(Array(0...6).windowed(size: 2, step: 1))
// => [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
print(Array(0...5).windowed(size: 2, step: 1))
// => [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
print(Array(0...5).windowed(size: 2, step: 1, partialWindows: true))
// => [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5]]
print(Array(0...5).chunked(size: 2))
// => [[0, 1], [2, 3], [4, 5]]
print(Array(0...4).chunked(size: 2))
// => [[0, 1], [2, 3]]
print(Array(0...4).chunked(size: 2, partialWindows: true))
// => [[0, 1], [2, 3], [4]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment