Last active
March 27, 2018 10:01
-
-
Save kakajika/dfcdafe835dd38a99c45a138faa23b11 to your computer and use it in GitHub Desktop.
Ported from Kotlin-stdlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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