Created
March 23, 2017 19:35
-
-
Save digoreis/efb8275d5ad673a6867671cbcb61d26c to your computer and use it in GitHub Desktop.
CircularQueue
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
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