Skip to content

Instantly share code, notes, and snippets.

@heestand-xyz
Created May 3, 2019 08:55
Show Gist options
  • Save heestand-xyz/36be68f74a40216f3ef8ff0e9b6df3d2 to your computer and use it in GitHub Desktop.
Save heestand-xyz/36be68f74a40216f3ef8ff0e9b6df3d2 to your computer and use it in GitHub Desktop.
Multi Filter Bypass
var filterCaches: [String: [CGFloat]] = [:]
func filter(_ value: CGFloat, for seconds: CGFloat, smooth: Bool = true, bypassLow: Bool = false, bypassHigh: Bool = false, id: String) -> CGFloat {
guard filterCaches[id] != nil else {
filterCaches[id] = [value]
return value
}
filterCaches[id]!.append(value)
let frameCount = Int(seconds * CGFloat(60))
while 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
}
if bypassLow {
var lower: CGFloat? = nil
for val in filterCaches[id]! {
if lower == nil || val < lower! {
lower = val
}
}
if value <= lower! {
for i in 0..<filterCaches[id]!.count {
filterCaches[id]![i] = value
}
return value
}
}
if bypassHigh {
var higher: CGFloat? = nil
for val in filterCaches[id]! {
if higher == nil || val > higher! {
higher = val
}
}
if value >= higher! {
for i in 0..<filterCaches[id]!.count {
filterCaches[id]![i] = value
}
return value
}
}
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