Skip to content

Instantly share code, notes, and snippets.

@dudo
Created February 10, 2020 17:12
Show Gist options
  • Select an option

  • Save dudo/8dcbdfadffa424f77d353cc613ee14d9 to your computer and use it in GitHub Desktop.

Select an option

Save dudo/8dcbdfadffa424f77d353cc613ee14d9 to your computer and use it in GitHub Desktop.

The 4 simple math functions

Lerp

Lerp is the acronym for linear interpolation. The idea is very simple, you have 2 values, and you want to “walk” between those values by a factor.

func lerp = (start, end, factor) => 
  start * (1-factor) + end * factor;

If you pass a factor of 0, you are pointing to the beginning of the walk so the value is equal to start. If you pass a factor of 1, you are pointing to the end of the walk so the value is equal to end. Any factor between 0 and 1 will add a (1-factor) of start argument and a factor of end argument. (e.g with start 0 and end 10 with a factor 0.5 you will have a 5, so the half of the path)

Normalize or Inverse Lerp

func normalize = (start, end, value) => 
  (value - start) / (end - start);

This function is the opposite of lerp. Instead of a range and a factor, we give a range and a value to find out the factor.

MapValue

func mapValue = (value, fromMin, fromMax, toMin, toMax) => { 
  const factor = normalize(fromMin, fromMax, value);
  return lerp(toMin, toMax, factor);
}

As you can see and guess it converts a value from the scale [fromMin, fromMax] to a value from the scale[toMin, toMax]. It’s just the normalize and lerp functions working together.

Clamp

func clamp = (value, min, max) => 
  Math.min(Math.max(value, min), max);

It limits the value to the scale [min, max]. Any value that is more than the max will turn max. If it’s less than min will turn min.

@dudo
Copy link
Author

dudo commented Feb 10, 2020

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