Write an almost equals function and use it in the linear scale. Added a test for this new function.

This commit is contained in:
Evert Timberg 2016-02-06 09:38:44 -05:00
parent 73300e91c4
commit 61ca178e2b
3 changed files with 17 additions and 1 deletions

View File

@ -264,6 +264,9 @@
helpers.isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
helpers.almostEquals = function(x, y, epsilon) {
return Math.abs(x - y) < epsilon;
};
helpers.max = function(array) {
return array.reduce(function(max, value) {
if (!isNaN(value)) {

View File

@ -183,7 +183,13 @@
var niceMin = Math.floor(this.min / spacing) * spacing;
var niceMax = Math.ceil(this.max / spacing) * spacing;
var numSpaces = Math.ceil((niceMax - niceMin) / spacing);
var numSpaces = (niceMax - niceMin) / spacing;
// If very close to our rounded value, use it.
if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
numSpaces = Math.round(numSpaces);
} else {
numSpaces = Math.ceil(numSpaces);
}
// Put the values into the ticks array
this.ticks.push(this.options.ticks.min !== undefined ? this.options.ticks.min : niceMin);

View File

@ -329,6 +329,13 @@ describe('Core helper tests', function() {
expect(helpers.log10(1000)).toBeCloseTo(3, 1e-9);
});
it('should correctly determine if two numbers are essentially equal', function() {
expect(helpers.almostEquals(0, Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
expect(helpers.almostEquals(1, 1.1, 0.0001)).toBe(false);
expect(helpers.almostEquals(1e30, 1e30 + Number.EPSILON, 0)).toBe(false);
expect(helpers.almostEquals(1e30, 1e30 + Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
});
it('Should generate ids', function() {
expect(helpers.uid()).toBe('chart-0');
expect(helpers.uid()).toBe('chart-1');