Created
July 21, 2013 17:03
-
-
Save Rich-Harris/6049159 to your computer and use it in GitHub Desktop.
Threshold scale generator, similar to D3's
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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