diff --git a/src/scales/scale.category.js b/src/scales/scale.category.js index 175bd3e8fde..28f57b082c9 100644 --- a/src/scales/scale.category.js +++ b/src/scales/scale.category.js @@ -1,5 +1,5 @@ import Scale from '../core/core.scale'; -import {isNullOrUndef, valueOrDefault} from '../helpers'; +import {isNullOrUndef, valueOrDefault, _limitValue} from '../helpers'; const addIfString = (labels, raw, index) => typeof raw === 'string' ? labels.push(raw) - 1 @@ -14,6 +14,8 @@ function findOrAddLabel(labels, raw, index) { return first !== last ? index : first; } +const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max); + export default class CategoryScale extends Scale { constructor(cfg) { @@ -29,8 +31,9 @@ export default class CategoryScale extends Scale { return null; } const labels = this.getLabels(); - return isFinite(index) && labels[index] === raw - ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw)); + index = isFinite(index) && labels[index] === raw ? index + : findOrAddLabel(labels, raw, valueOrDefault(index, raw)); + return validIndex(index, labels.length - 1); } determineDataLimits() { diff --git a/test/specs/scale.category.tests.js b/test/specs/scale.category.tests.js index 24bcf46b14b..fe3aad52e74 100644 --- a/test/specs/scale.category.tests.js +++ b/test/specs/scale.category.tests.js @@ -20,7 +20,6 @@ describe('Category scale tests', function() { }); }); - it('Should generate ticks from the data xLabels', function() { var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']; var chart = window.acquireChart({ @@ -114,6 +113,42 @@ describe('Category scale tests', function() { }); + it('should parse only to a valid index', function() { + var chart = window.acquireChart({ + type: 'line', + data: { + datasets: [{ + xAxisID: 'x', + yAxisID: 'y', + data: [10, 5, 0, 25, 78] + }], + labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'] + }, + options: { + scales: { + x: { + type: 'category', + position: 'bottom' + }, + y: { + type: 'linear' + } + } + } + }); + + var scale = chart.scales.x; + + expect(scale.parse(-10)).toEqual(0); + expect(scale.parse(-0.1)).toEqual(0); + expect(scale.parse(4.1)).toEqual(4); + expect(scale.parse(5)).toEqual(4); + expect(scale.parse(1)).toEqual(1); + expect(scale.parse(1.4)).toEqual(1); + expect(scale.parse(1.5)).toEqual(2); + expect(scale.parse('tick2')).toEqual(1); + }); + it('should get the correct label for the index', function() { var chart = window.acquireChart({ type: 'line',