Skip to content

Instantly share code, notes, and snippets.

@aubergene
Last active August 15, 2016 13:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aubergene/7791133 to your computer and use it in GitHub Desktop.
Save aubergene/7791133 to your computer and use it in GitHub Desktop.
Simple JavaScript Scale

I love D3's Quantitative Scales and wanted a simple way to create and use scales in that style.

Example

var centigradeToFahrenheit = new Scale().domain(-40, 0).range(-40, 32);
var fahrenheitToCentigrade = new Scale().domain(-40, 32).range(-40, 0);

centigradeToFahrenheit(35); // 95 hot!
fahrenheitToCentigrade(14); // -10 cold!
// This is a function
function Normalizer(min, max) {
return function(val) {
return (val - min) / (max - min);
}
}
// This is another
function Interpolater(min, max, clamp) {
return function(val) {
val = min + (max - min) * val;
return clamp ? Math.min(Math.max(val, min), max) : val;
}
}
// This is a third
function Scale() {
var domain = new Normalizer(0, 1);
var range = new Interpolater(0, 1);
var s = function(val) {
return range(domain(val));
};
s.domain = function(min, max) {
if (!arguments.length) return domain;
domain = new Normalizer(min, max)
return s
};
s.range = function(min, max, clamp) {
if (!arguments.length) return range;
range = new Interpolater(min, max, clamp)
return s
};
return s;
}
// Now form a visualization
// ========================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment