CategoryScale: automatically add missing labels (#8053)

CategoryScale: automatically add missing labels
This commit is contained in:
Jukka Kurkela
2020-11-15 00:00:17 +02:00
committed by GitHub
parent fde84f272a
commit ef89abb84b
3 changed files with 35 additions and 7 deletions

View File

@@ -1,5 +1,14 @@
import Scale from '../core/core.scale';
function findOrAddLabel(labels, raw, index) {
const first = labels.indexOf(raw);
if (first === -1) {
return typeof raw === 'string' ? labels.push(raw) - 1 : index;
}
const last = labels.lastIndexOf(raw);
return first !== last ? index : first;
}
export default class CategoryScale extends Scale {
constructor(cfg) {
@@ -12,12 +21,8 @@ export default class CategoryScale extends Scale {
parse(raw, index) {
const labels = this.getLabels();
if (labels[index] === raw) {
return index;
}
const first = labels.indexOf(raw);
const last = labels.lastIndexOf(raw);
return first === -1 || first !== last ? index : first;
return isFinite(index) && labels[index] === raw
? index : findOrAddLabel(labels, raw, index);
}
determineDataLimits() {

View File

@@ -2,7 +2,6 @@ module.exports = {
config: {
type: 'bar',
data: {
labels: [0, 1, 3, 4],
datasets: [
{
data: {0: 5, 1: 20, 2: 1, 3: 10},

View File

@@ -90,6 +90,30 @@ describe('Category scale tests', function() {
expect(getLabels(scale)).toEqual(labels);
});
it('Should generate missing labels', function() {
var labels = ['a', 'b', 'c', 'd'];
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: {a: 1, b: 3, c: -1, d: 10}
}]
},
options: {
scales: {
x: {
type: 'category',
labels: ['a']
}
}
}
});
var scale = chart.scales.x;
expect(getLabels(scale)).toEqual(labels);
});
it('should get the correct label for the index', function() {
var chart = window.acquireChart({
type: 'line',