Skip to content

Instantly share code, notes, and snippets.

@andrewluetgers
Last active March 1, 2016 23:22
Show Gist options
  • Save andrewluetgers/2d0c30784e88b1cc5c88 to your computer and use it in GitHub Desktop.
Save andrewluetgers/2d0c30784e88b1cc5c88 to your computer and use it in GitHub Desktop.
Convert a number in domain A to domain B
// a normalize function constructor for mapping from one range of numbers to another
// actually it is 4 ranges, one from mid to max another from min to mid for each domain
// so given 3 input (domainA) numbers for min, mid, max
// and given 3 output (domainB) numbers or arrays of any length of numbers also for min, mid, max
// the constructor function will return a normalize function that wil convert any number in domainA to domainB
//
// example:
// converting a value from -1 to 1 to a color ramp red to green
// with a white neutral in the middle and alpha evenly interpolated
//
// example constructor call:
// var n = normalizer(-1, 0, 1, [255,0,0,1], [255, 255, 255, 0], [0, 255, 0, 1]);
//
// example usage of normalize function:
// n(1) -> [0, 255, 0, 1]
// n(-1) -> [255, 0, 0, 1]
// n(0) -> [255, 255, 255, 0]
// n(.5) -> [127.5, 255, 127.5, 0.5]
//
normalizer = (function() {
function _normalize(rangeA, rangeB, xInRangeA) {
// returns x of a in range of b
// http://stackoverflow.com/questions/1471370/normalizing-from-0-5-1-to-0-1#answer-17029736
return ((rangeB[1] - rangeB[0]) * (xInRangeA - rangeA[0]))/(rangeA[1] - rangeA[0]) + rangeB[0];
}
return function normalizer(minVal, midVal, maxVal, min, mid, max) {
return function normalize(val) {
var rangeA, rangeB;
if (val > midVal) {
rangeA = [midVal, maxVal];
rangeB = [mid, max];
} else {
rangeA = [minVal, midVal];
rangeB = [min, mid];
}
if (typeof max == "number") {
return _normalize(rangeA, rangeB, val);
} else if (max.map) {
return rangeB[0].map((v, i) => {
return _normalize(rangeA, [rangeB[0][i], rangeB[1][i]], val);
});
} else {
throw new Error("Expecting number or array of numbers but saw: " + typeof max)
}
};
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment