nice-buckets
Version:
Get a list of n sub-ranges that contain a range. Or something.
100 lines (92 loc) • 2.87 kB
JavaScript
// Generated by CoffeeScript 1.7.1
(function() {
var magic, minFigs, root;
magic = function(stops, range, intervals) {
var bucket, highest, interval, lowest, magnitude, max, min, n, smallest, _i, _j, _len, _ref, _results;
if (intervals == null) {
intervals = [1, 1.2, 1.5, 1.6, 2, 2.5, 3, 5, 8];
}
lowest = range[0], highest = range[1];
smallest = (highest - lowest) / stops;
if (smallest === 0) {
return [range];
}
magnitude = Math.pow(10, Math.floor((Math.log(smallest)) / Math.log(10)));
for (_i = 0, _len = intervals.length; _i < _len; _i++) {
interval = intervals[_i];
bucket = interval * magnitude;
if (bucket < smallest) {
continue;
}
min = bucket * (Math.floor(lowest / bucket));
max = min + (bucket * stops);
if (max >= highest) {
break;
}
}
_results = [];
for (n = _j = 0, _ref = stops - 1; 0 <= _ref ? _j <= _ref : _j >= _ref; n = 0 <= _ref ? ++_j : --_j) {
_results.push((function(m) {
return [m, m + bucket];
})(min + bucket * n));
}
return _results;
};
minFigs = function(stops, range, maxOut, base) {
var bucket, highest, lowest, n, nicify, precision, r, _i, _ref, _results;
if (maxOut == null) {
maxOut = 0.99;
}
if (base == null) {
base = 10;
}
lowest = range[0], highest = range[1];
bucket = (highest - lowest) / stops;
if (bucket === 0) {
return [range];
}
precision = Infinity;
nicify = function(n, k) {
var min, p, q;
p = Math.pow(base, Math.floor((Math.log(k)) / Math.log(base)));
q = base * p;
min = q * Math.floor(n / q);
if (q < precision) {
precision = q;
}
if (min < n - k) {
min = p * Math.floor(n / p);
if (p < precision) {
precision = p;
}
}
return min;
};
lowest = nicify(lowest, maxOut * bucket);
bucket = (highest - lowest) / stops;
bucket = nicify(bucket + (bucket / stops), bucket / stops);
r = function(n) {
return Math.round(n / precision) / (1 / precision);
};
_results = [];
for (n = _i = 0, _ref = stops - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; n = 0 <= _ref ? ++_i : --_i) {
_results.push((function(m) {
return [r(m), r(m + bucket)];
})(lowest + bucket * n));
}
return _results;
};
root = {
magic: magic,
minFigs: minFigs
};
if (!((typeof module !== "undefined" && module !== null) || (typeof requirejs !== "undefined" && requirejs !== null))) {
this.buckets = root;
}
if (typeof module !== "undefined" && module !== null) {
module.exports = root;
}
if ((typeof requirejs !== "undefined" && requirejs !== null) && (typeof define !== "undefined" && define !== null)) {
define(root);
}
}).call(this);