-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLimitedArray.swift
More file actions
43 lines (37 loc) · 1.22 KB
/
Copy pathLimitedArray.swift
File metadata and controls
43 lines (37 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
struct LimitedArray<T> {
private(set) var storage: [T] = [T]()
public let maxSize: Int
public var count: Int {
return storage.count
}
/// creates an empty array
public init(maxSize: Int) {
self.maxSize = maxSize
}
/// adds a new item to the array, if the array has reached its maximum capacity we remove the first one (the oldest value)
public mutating func append(_ item: T) {
if storage.count < maxSize {
storage.append(item)
} else {
storage.removeFirst()
storage.append(item)
}
}
}
// let's benefit all the awesome operations like map, flatMap, reduce, filter, etc
extension LimitedArray: MutableCollection {
public var startIndex: Int { return storage.startIndex }
public var endIndex: Int { return storage.endIndex }
public subscript(_ index: Int) -> T {
get { return storage[index] }
set { storage[index] = newValue }
}
public func index(after i: Int) -> Int {
return storage.index(after: i)
}
}
extension LimitedArray: CustomStringConvertible {
var description: String {
return "[" + self.storage.map{"\"\($0)\""}.joined(separator: ", ") + "]"
}
}