Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created May 26, 2018 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/f0f1a860004d4e97b21f0f0e9309ceca to your computer and use it in GitHub Desktop.
Save khanlou/f0f1a860004d4e97b21f0f0e9309ceca to your computer and use it in GitHub Desktop.
public extension BinaryFloatingPoint {
public func scaled(from source: ReversibleRange<Self>, to destination: ReversibleRange<Self>) -> Self {
let destinationStart = destination.lowerBound
let destinationEnd = destination.upperBound
let selfMinusLower = self - source.lowerBound
let sourceUpperMinusLower = source.upperBound - source.lowerBound
let destinationUpperMinusLower = destinationEnd - destinationStart
let percentThroughSource = (selfMinusLower / sourceUpperMinusLower)
let curvedPercent = percentThroughSource
return curvedPercent * destinationUpperMinusLower + destinationStart
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment