Skip to content

Instantly share code, notes, and snippets.

@dfelber
Last active March 20, 2016 14:03
Show Gist options
  • Save dfelber/a52b6ac1eb1c8dd2c332 to your computer and use it in GitHub Desktop.
Save dfelber/a52b6ac1eb1c8dd2c332 to your computer and use it in GitHub Desktop.
Convert a value from one number range into another one. e.g.: 50.remap(from: (min: 0.0, max: 100.0), to: (min: 0.0, max: 1.0)) => 0.5
protocol Numeric: SignedNumberType
{
func * (lhs: Self, rhs: Self) -> Self
func + (lhs: Self, rhs: Self) -> Self
func - (lhs: Self, rhs: Self) -> Self
func / (lhs: Self, rhs: Self) -> Self
}
extension Numeric
{
func remap(from from: (min: Self, max: Self), to: (min: Self, max: Self)) -> Self?
{
return remapValue(self, from: (min: from.min, max: from.max), to: (min: to.min, max: to.max))
}
}
func remapValue <T: Numeric> (input: T, from: (min: T, max: T), to: (min: T, max: T)) -> T?
{
let div = from.max - from.min
guard div > 0 else
{
return nil
}
return (input - from.min) / div * (to.max - to.min) + to.min
}
extension CGFloat: Numeric {}
extension Float: Numeric {}
extension Double: Numeric {}
// example usage
let a = 0.123.remap(from: (min: 0.0, max: 1.0), to: (min: 100.0, max: 200.0)) // a = 112.3
let b = remapValue(12.0, from: (0.0, 100.0), to: (0.0, 1.0)) // b = 0.12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment