-
Notifications
You must be signed in to change notification settings - Fork 0
/
RunningBuffer.swift
73 lines (57 loc) · 1.51 KB
/
RunningBuffer.swift
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This class manages a running buffer of Double values.
*/
import Foundation
class RunningBuffer {
// MARK: Properties
var buffer = [Double]()
var size = 0
// MARK: Initialization
init(size: Int) {
self.size = size
self.buffer = [Double](repeating: 0.0, count: self.size)
}
// MARK: Running Buffer
func addSample(_ sample: Double) {
buffer.insert(sample, at:0)
if buffer.count > size {
buffer.removeLast()
}
}
func reset() {
buffer.removeAll(keepingCapacity: true)
}
func isFull() -> Bool {
return size == buffer.count
}
func sum() -> Double {
return buffer.reduce(0.0, +)
}
func min() -> Double {
var min = 0.0
if let bufMin = buffer.min() {
min = bufMin
}
return min
}
func max() -> Double {
var max = 0.0
if let bufMax = buffer.max() {
max = bufMax
}
return max
}
func recentMean() -> Double {
// Calculate the mean over the beginning half of the buffer.
let recentCount = self.size / 2
var mean = 0.0
if (buffer.count >= recentCount) {
let recentBuffer = buffer[0..<recentCount]
mean = recentBuffer.reduce(0.0, +) / Double(recentBuffer.count)
}
return mean
}
}