Skip to content

Instantly share code, notes, and snippets.

@elcoreman
Last active February 3, 2023 17:05
Show Gist options
  • Save elcoreman/7a92c9c20855a8973f20cabd9a8ab0a1 to your computer and use it in GitHub Desktop.
Save elcoreman/7a92c9c20855a8973f20cabd9a8ab0a1 to your computer and use it in GitHub Desktop.
Scale number from range A to range B

Sometimes we need to transfer a number from range A to range B
I wrote this in ts but you can easily change it to your preferred language
hope this save your time.

type Scale = (
  number: number,
  from: [number, number],
  to: [number, number]
) => number;

const scale: Scale = (number, from, to) => {
  const stepCost = (to[1] - to[0]) / (from[1] - from[0]);
  const startOffset = number - from[0];
  const newNumber = startOffset * stepCost + to[0];
  return newNumber;
};

scale(5, [0, 10], [0, 100]); // return: 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment