Skip to content

Instantly share code, notes, and snippets.

@misablaha
Created February 20, 2020 09:25
Show Gist options
  • Save misablaha/5d21bf3237035e4ec78560380c5445cd to your computer and use it in GitHub Desktop.
Save misablaha/5d21bf3237035e4ec78560380c5445cd to your computer and use it in GitHub Desktop.
const map = [
[4690, 0],
[4648, 20.0],
[4480, 30.0],
[4340, 45.0],
[4172, 60.0],
[3976, 80.0],
[3752, 100.0],
[3276, 150.0],
[2772, 200.0],
[2268, 250.0],
[2100, 270.0],
[1876, 290.0],
[1736, 305.0],
[1596, 320.0],
[1484, 330.0],
[1372, 340.0],
[1260, 350.0],
[1148, 360.0],
[1092, 370.0],
[1008, 380.0],
[896, 390.0],
[784, 400.0],
[700, 410.0],
[588, 420.0],
[476, 430.0],
[392, 440.0],
[336, 445.0],
[0, 450.0]
];
/**
* Rescale value between 2 ranges
*
* (dstMax-dstMin) * (x - srcMin)
* f(x) = ------------------------------ + dstMin
* srcMax - srcMin
*/
const scale = (src, dst, val) => {
return (dst[1] - dst[0]) * (val - src[0]) / (src[1] - src[0]) + dst[0];
}
const isBetween = (bounds, val) => Math.min(...bounds) <= val && val <= Math.max(...bounds)
const isDecrease = (a, b) => (a - b) < 0
const isIncrease = (a, b) => (a - b) > 0
const interpolate = (pts, val) => {
if (!Array.isArray(pts)) {
throw new TypeError('Points map must be type of array.')
}
const isOrdered = (pts[0][0] - pts[1][0]) > 0 ? isDecrease : isIncrease
let prev = pts[0];
for (let i = 1; i < pts.length; i += 1) {
if (isOrdered(prev[0], pts[i][0])) {
throw new Error('Points map must be ordered.');
}
if (isBetween([prev[0], pts[i][0]], val)) {
return scale([prev[0], pts[i][0]], [prev[1], pts[i][1]], val)
}
prev = pts[i];
}
throw new RangeError(`Value ${val} is out of range ${pts[0][0]}..${prev[0]}`);
}
const pc = 68;
const mm = scale([0, 100], [map[0][0], map[map.length - 1][0]], pc);
const lt = interpolate(map, mm);
console.log(mm);
console.log(lt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment