Created
August 13, 2018 02:45
-
-
Save ahti/ed9df5e33952a773679853b26f219798 to your computer and use it in GitHub Desktop.
This file contains 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
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