Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Created December 15, 2016 10:45
Show Gist options
  • Save Anthodpnt/aafeb0dc669fb9137dd0550b6f5d8630 to your computer and use it in GitHub Desktop.
Save Anthodpnt/aafeb0dc669fb9137dd0550b6f5d8630 to your computer and use it in GitHub Desktop.
Math - Normalization
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <antho.dpnt@gmail.com>
* @site: https://www.twitter.com/JsGists
*
* It's very common in Javascript to normalize numbers. Normalization means that you are taking a number from a range
* and return a value from 0 to 1 corresponding to the position of this number within this range.
*
* If the number is equal to the minimum value of the range, the normal value is 0.
* If the number is equal to the maximum value of the range, the normal value is 1.
* If the number is equal to any value in the range, the normal value is any value between 0 and 1.
*
* The main idea is to convert this number to a value from 0 to 1. This is really useful for calculation in Javascript.
*
* Example:
* I have a range [20, 40] and I want to get the normal value of 23.
**/
const range = [20, 40];
const value = 23;
const normal = norm(value, range[0], range[1]); // Return 0.15
function norm(value, min, max) {
return (value - min) / (max - min);
}
// Let's check the result in the console.
console.log(normal);
Copy link

ghost commented Dec 11, 2021

nice!
a linear scale function for input range of 0-1.
its much shorter than the extended version!
(although with the extended version you can also scale back and forth, provided you know the input range)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment