Swift 3
With Bool for extended range or not
func translate(input : Float, inputMin: Float, inputMax: Float, outputMin: Float, outputMax: Float, extendRange: Bool? = false, log: Bool? = false) -> Float {
//The actual translation function
func translationResult(_ inputMinA: Float, _ inputMaxA: Float) -> Float {
let myResult = outputMin + (outputMax - outputMin) * (input - inputMinA) / (inputMaxA - inputMinA)
return myResult
}
// extendRange true means it'll return a value outside the range of inputMin and inputMax but still follow the ratio
if extendRange! {
return result = translationResult(inputMin, inputMax)
if log! == true && input > inputMax || input < inputMin{
print("outside range!")
}
} else {
//Doesn't let value go outside range
let inputMinA = min(inputMin, input)
let inputMaxA = max(inputMax, input)
return result = translationResult(inputMinA, inputMaxA)
}
}
translate(input: 50, inputMin: 100, inputMax: 1000.0, outputMin: 1, outputMax: 10, extendRange: false) => 1
translate(input: 50, inputMin: 100, inputMax: 1000.0, outputMin: 1, outputMax: 10, extendRange: true) => 0.5