Skip to content

Instantly share code, notes, and snippets.

@ahti
Created August 13, 2018 02:45
Show Gist options
  • Save ahti/ed9df5e33952a773679853b26f219798 to your computer and use it in GitHub Desktop.
Save ahti/ed9df5e33952a773679853b26f219798 to your computer and use it in GitHub Desktop.
struct SlidingWindowView<C: RandomAccessCollection>: RandomAccessCollection {
enum EndBehavior {
case stop
case truncate
}
let base: C
let windowSize: Int
let stepSize: Int
let endBehavior: EndBehavior
var startIndex: Int {
return 0
}
var endIndex: Int {
switch endBehavior {
case .stop:
return Swift.max(base.count - windowSize, -1) / stepSize + 1
case .truncate:
return (base.count + stepSize - 1) / stepSize
}
}
subscript(_ pos: Int) -> C.SubSequence {
get {
let offset = pos * stepSize
let start = base.index(base.startIndex, offsetBy: offset)
let end: C.Index
switch endBehavior {
case .stop:
end = base.index(start, offsetBy: windowSize)
case .truncate:
end = base.index(start, offsetBy: windowSize, limitedBy: base.endIndex) ?? base.endIndex
}
return base[start..<end]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment