Skip to content

Instantly share code, notes, and snippets.

@brendanmoore
Forked from remy/map.js
Created April 8, 2014 09:41
Show Gist options
  • Save brendanmoore/10104918 to your computer and use it in GitHub Desktop.
Save brendanmoore/10104918 to your computer and use it in GitHub Desktop.
function map(x, in_min, in_max, out_min, out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Directly ported/pinched from Arduino reference.

This simple example converts the gamma range from the device orientation event from a floating point between -90 and +90 to an unsigned int (via | 0) between -5 and +5:

window.addEventListener('deviceorientation', function (event) {
  var g = map(event.gamma, -90, 90, -5, 5) | 0;
  el.innerHTML = ['\ngamma', g].join(' ');
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment