Skip to content

Instantly share code, notes, and snippets.

@nevernotsean
Forked from remy/map.js
Last active March 8, 2019 16:39
Show Gist options
  • Save nevernotsean/e367a1e62458de0ca9983cfdf485e454 to your computer and use it in GitHub Desktop.
Save nevernotsean/e367a1e62458de0ca9983cfdf485e454 to your computer and use it in GitHub Desktop.
function linearmap(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