Skip to content

Instantly share code, notes, and snippets.

@peeke
Last active March 13, 2019 12:48
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 peeke/f7542d36d225a47ba7dda7ce501f539b to your computer and use it in GitHub Desktop.
Save peeke/f7542d36d225a47ba7dda7ce501f539b to your computer and use it in GitHub Desktop.
Method to map a number from an input domain to an output range. Useful for animations based on userinput.
// This clamp function does not need left to be smaller than right, making it better suited for animations
const clamp = (input, left, right) => {
if (left > right) {
[left, right] = [right, left]
}
return Math.min(Math.max(input, left), right)
}
export default clamp
const lerp = (a, b, weight) => a + weight * (b - a)
export default lerp
import clamp from 'clamp'
import lerp from 'linear-interpolate'
const mapNumber = (input, inFrom, inTo, outFrom, outTo) => {
input = clamp(input, inFrom, inTo)
const t = (input - inFrom) / (inTo - inFrom)
return lerp(outFrom, outTo, t)
}
export default mapNumber
// mapNumber(1, 0, 10, 10, 30) outputs 12
// mapNumber(5, 0, 10, 10, 30) outputs 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment