Last active
August 22, 2019 13:00
-
-
Save RayPS/9ffe2dd2a85a6c13333c1161dba29149 to your computer and use it in GitHub Desktop.
Swift modulate CGFloat between two ranges.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension CGFloat { | |
func modulate(from: [CGFloat], to: [CGFloat], limit: Bool) -> CGFloat { | |
let result = to[0] + (((self - from[0]) / (from[1] - from[0])) * (to[1] - to[0])) | |
return limit ? [[result, to.min()!].max()!, to.max()!].min()! : result | |
} | |
} |
JavaScript:
const modulate = (value, from, to, limit = false) => {
const result = to[0] + (((value - from[0]) / (from[1] - from[0])) * (to[1] - to[0]))
return limit ? Math.min(Math.max(result, Math.min(...to)), Math.max(...to)) : result
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: