Skip to content

Instantly share code, notes, and snippets.

@stekhn
Last active January 7, 2020 20:34
Show Gist options
  • Select an option

  • Save stekhn/aa5b03f693270344cba58d9306e7f6f3 to your computer and use it in GitHub Desktop.

Select an option

Save stekhn/aa5b03f693270344cba58d9306e7f6f3 to your computer and use it in GitHub Desktop.
Map a continuous value within a certain domain to a discrete value in JavaScript. Great for maps where you need to find a certain color for a given value.
const quantizeScale = (arr, min, max) => {
const steps = colors.length;
const increment = (max - min) / steps;
const bins = Array.apply(undefined, Array(steps)).map((bin, index) => (index * increment) + min);
return value => {
for (let i = 0; i < bins.length; i++) {
if (value <= bins[i]) {
return colors[i];
}
}
return colors[colors.length - 1];
};
};
// Discrete color scale from light blue to dark blue
const colors = ['#f1eef6', '#bdc9e1', '#74a9cf', '#2b8cbe', '#045a8d'];
const minimum = 5;
const maximum = 20;
// Construct new scale
const quantize = quantizeScale(colors, minimum, maximum);
console.log(quantize(0)); // => #f1eef6
console.log(quantize(5)); // => #f1eef6
console.log(quantize(10)); // => #74a9cf
console.log(quantize(15)); // => #045a8d
console.log(quantize(20)); // => #045a8d
console.log(quantize(100)); // => #045a8d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment