mirror of
https://github.com/chartjs/Chart.js.git
synced 2026-03-06 00:14:03 +01:00
CategoryScale: automatically add missing labels (#8053)
CategoryScale: automatically add missing labels
This commit is contained in:
@@ -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() {
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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',
|
||||
|
||||
Reference in New Issue
Block a user