Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Created July 21, 2013 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/6049159 to your computer and use it in GitHub Desktop.
Save Rich-Harris/6049159 to your computer and use it in GitHub Desktop.
Threshold scale generator, similar to D3's
(function ( global ) {
'use strict';
// Threshold scale generator, similar to D3's
// Usage:
//
// scale = thresholdScale([ 0, 20, 40, 100 ], [ 'red', 'green', 'blue' ]);
// scale( 10 ) -> 'red'
var thresholdScale = function ( domain, range ) {
var d0, d1;
if ( domain.length !== range.length + 1 ) {
throw new Error( 'Range must have one more value than domain' );
}
d0 = domain[0];
d1 = domain[ domain.length - 1 ];
return function ( val ) {
var i, result;
// if value is outside domain, return undefined
if ( val < d0 || val > d1 ) {
return undefined;
}
i = 0;
//result = domain[0];
while ( val > domain[i] ) {
result = range[i];
i += 1;
}
return result;
};
};
// export as CommonJS module...
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = thresholdScale;
}
// ... or as AMD module...
else if ( typeof define !== 'undefined' && define.amd ) {
define( function () { return thresholdScale; });
}
// ... or as browser global
else {
global.thresholdScale = thresholdScale;
}
}( this ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment