Last active
April 30, 2019 07:47
-
-
Save heestand-xyz/d8aee289b7700b0ab3761e1198ffeb73 to your computer and use it in GitHub Desktop.
Multi Filter
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
var filterCaches: [String: [CGFloat]] = [:] | |
func filter(_ value: CGFloat, for seconds: CGFloat, smooth: Bool = true, id: String) -> CGFloat { | |
guard filterCaches[id] != nil else { | |
filterCaches[id] = [value] | |
return value | |
} | |
filterCaches[id]!.append(value) | |
let frameCount = Int(seconds * CGFloat(60)) | |
if filterCaches[id]!.count > frameCount { | |
filterCaches[id]!.remove(at: 0) | |
} | |
guard filterCaches[id]!.count > 1 else { | |
return filterCaches[id]![0] | |
} | |
guard filterCaches[id]!.count > 2 else { | |
return (filterCaches[id]![0] + filterCaches[id]![1]) / 2 | |
} | |
var filteredValue: CGFloat = 0.0 | |
var weight: CGFloat = smooth ? 0.0 : CGFloat(filterCaches[id]!.count) | |
for (i, val) in filterCaches[id]!.enumerated() { | |
let fraction = CGFloat(i) / CGFloat(filterCaches[id]!.count - 1) | |
let smoothWeight: CGFloat = 1.0 - (cos(fraction * .pi * 2) / 2 + 0.5) | |
filteredValue += val * (smooth ? smoothWeight : 1.0) | |
weight += smoothWeight | |
} | |
filteredValue /= weight | |
return filteredValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment