Last active
July 12, 2017 03:22
-
-
Save dsuket/51129efc9f20b9a0dd18 to your computer and use it in GitHub Desktop.
js scale like D3
This file contains hidden or 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() { | |
/** | |
Usage: | |
```javascript | |
var userScale = scale() | |
.domain(0, 10) | |
.range(0,100); | |
userScale(2); | |
// => 20 | |
userScale.range(100, 0); | |
userScale(2); | |
// => 80 | |
``` | |
*/ | |
function scale() { | |
var domain = []; | |
var range = []; | |
var _scale = function(x) { | |
if (domain.length < 2) {return _scale;} | |
if (range.length < 2) {return _scale;} | |
x = Math.max(x, domain.min); | |
x = Math.min(x, domain.max); | |
var x2 = distance(domain[0], x); | |
var rangeVal = x2/domain.distance * range.distance; | |
return range[0] + rangeVal; | |
}; | |
function distance(x1, x2) { | |
if (x1 instanceof Array) { | |
x2 = x1[1]; | |
x1 = x1[0]; | |
} | |
// return Math.max(x1, x2) - Math.min(x1, x2); | |
return x2 - x1; | |
} | |
function initDistance(obj) { | |
obj.distance = distance(obj); | |
obj.min = Math.min.apply(Math, obj); | |
obj.max = Math.max.apply(Math, obj); | |
return obj; | |
} | |
_scale.domain = function(/* start, end */) { | |
domain = Array.prototype.slice.call(arguments, 0, 2); | |
initDistance(domain); | |
return _scale; | |
}; | |
_scale.range = function(/* start, end */) { | |
range = Array.prototype.slice.call(arguments, 0, 2); | |
initDistance(range); | |
return _scale; | |
}; | |
return _scale; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment