Skip to content

Instantly share code, notes, and snippets.

@juliengdt
Created July 4, 2019 14:52
Show Gist options
  • Save juliengdt/0761e5a17a960a7974df255abea2f387 to your computer and use it in GitHub Desktop.
Save juliengdt/0761e5a17a960a7974df255abea2f387 to your computer and use it in GitHub Desktop.
Put any numeral between two intervals, exactly like a numeric compass [0° <-> 360°] behavior.
extension Numeric where Self: Comparable /* NORMALIZER */ {
/// normalize the current value between a min and a max interval, by adding optionaly a value. this works just like the compass normalization. for Ex, 357°, by adding +4 became 1° for [0 - 360] interval
///
/// - Parameters:
/// - value: the value to add
/// - min: the minimum interval
/// - max: the maximum interval
/// - Returns: the new, transformed and normalized value
func norm(byAdding value: Self,_ min: Self = 0, _ max: Self = 360) -> Self {
let this = self + value
return this.norm(min, max)
}
/// normalize the current value between a min and a max interval. This works just like the compass normalization. for Ex, -1° became 359° for [0 - 360] interval
///
/// - Parameters:
/// - min: the minimum interval
/// - max: the maximum interval
/// - Returns: the new, transformed and normalized value
func norm(_ min: Self = 0, _ max: Self = 360) -> Self {
var this = self
while this < min {
this += max
}
while this > max {
this -= max
}
return this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment