Skip to content

Commit e51a401

Browse files
authored
Category: parse to valid index values only (#8697)
1 parent 9499a1e commit e51a401

File tree

2 files changed

+42
-4
lines changed

2 files changed

+42
-4
lines changed

src/scales/scale.category.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Scale from '../core/core.scale';
2-
import {isNullOrUndef, valueOrDefault} from '../helpers';
2+
import {isNullOrUndef, valueOrDefault, _limitValue} from '../helpers';
33

44
const addIfString = (labels, raw, index) => typeof raw === 'string'
55
? labels.push(raw) - 1
@@ -14,6 +14,8 @@ function findOrAddLabel(labels, raw, index) {
1414
return first !== last ? index : first;
1515
}
1616

17+
const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);
18+
1719
export default class CategoryScale extends Scale {
1820

1921
constructor(cfg) {
@@ -29,8 +31,9 @@ export default class CategoryScale extends Scale {
2931
return null;
3032
}
3133
const labels = this.getLabels();
32-
return isFinite(index) && labels[index] === raw
33-
? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
34+
index = isFinite(index) && labels[index] === raw ? index
35+
: findOrAddLabel(labels, raw, valueOrDefault(index, raw));
36+
return validIndex(index, labels.length - 1);
3437
}
3538

3639
determineDataLimits() {

test/specs/scale.category.tests.js

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ describe('Category scale tests', function() {
2020
});
2121
});
2222

23-
2423
it('Should generate ticks from the data xLabels', function() {
2524
var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
2625
var chart = window.acquireChart({
@@ -114,6 +113,42 @@ describe('Category scale tests', function() {
114113

115114
});
116115

116+
it('should parse only to a valid index', function() {
117+
var chart = window.acquireChart({
118+
type: 'line',
119+
data: {
120+
datasets: [{
121+
xAxisID: 'x',
122+
yAxisID: 'y',
123+
data: [10, 5, 0, 25, 78]
124+
}],
125+
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
126+
},
127+
options: {
128+
scales: {
129+
x: {
130+
type: 'category',
131+
position: 'bottom'
132+
},
133+
y: {
134+
type: 'linear'
135+
}
136+
}
137+
}
138+
});
139+
140+
var scale = chart.scales.x;
141+
142+
expect(scale.parse(-10)).toEqual(0);
143+
expect(scale.parse(-0.1)).toEqual(0);
144+
expect(scale.parse(4.1)).toEqual(4);
145+
expect(scale.parse(5)).toEqual(4);
146+
expect(scale.parse(1)).toEqual(1);
147+
expect(scale.parse(1.4)).toEqual(1);
148+
expect(scale.parse(1.5)).toEqual(2);
149+
expect(scale.parse('tick2')).toEqual(1);
150+
});
151+
117152
it('should get the correct label for the index', function() {
118153
var chart = window.acquireChart({
119154
type: 'line',

0 commit comments

Comments
 (0)