Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created March 23, 2017 19:35
Show Gist options
  • Save digoreis/efb8275d5ad673a6867671cbcb61d26c to your computer and use it in GitHub Desktop.
Save digoreis/efb8275d5ad673a6867671cbcb61d26c to your computer and use it in GitHub Desktop.
CircularQueue
class CircularQueue<T> : IteratorProtocol, RandomAccessCollection {
typealias Element = T
public typealias Index = Int
public typealias Indices = CountableRange<Int>
var position = 0
let items : [T]
init(items:[T]){
self.items = items
}
func next() -> T? {
let item = items[position]
position = ((position + 1) % items.count)
return item
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return items.count
}
public func index(after i: Int) -> Int {
_precondition(i == startIndex)
return endIndex
}
public func index(before i: Int) -> Int {
_precondition(i == endIndex)
return startIndex
}
public subscript(position: Int) -> Element {
get {
let pos = (position % items.count)
return items[pos]
}
set {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment