Skip to content

Commit

Permalink
Fix category scale invalid data handling (#8668)
Browse files Browse the repository at this point in the history
* Fix category scale invalid data handling
* Fix NaN
  • Loading branch information
kurkle committed Mar 18, 2021
1 parent 97136d0 commit 851861e
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/scales/scale.category.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import Scale from '../core/core.scale';
import {valueOrDefault} from '../helpers';
import {isNullOrUndef, valueOrDefault} from '../helpers';

const addIfString = (labels, raw, index) => typeof raw === 'string'
? labels.push(raw) - 1
: isNaN(raw) ? null : index;

function findOrAddLabel(labels, raw, index) {
const first = labels.indexOf(raw);
if (first === -1) {
return typeof raw === 'string' ? labels.push(raw) - 1 : index;
return addIfString(labels, raw, index);
}
const last = labels.lastIndexOf(raw);
return first !== last ? index : first;
Expand All @@ -21,6 +25,9 @@ export default class CategoryScale extends Scale {
}

parse(raw, index) {
if (isNullOrUndef(raw)) {
return null;
}
const labels = this.getLabels();
return isFinite(index) && labels[index] === raw
? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
Expand Down Expand Up @@ -96,7 +103,7 @@ export default class CategoryScale extends Scale {
value = me.parse(value);
}

return me.getPixelForDecimal((value - me._startValue) / me._valueRange);
return value === null ? NaN : me.getPixelForDecimal((value - me._startValue) / me._valueRange);
}

// Must override base implementation because it calls getPixelForValue
Expand Down
41 changes: 41 additions & 0 deletions test/fixtures/scale.category/invalid-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
module.exports = {
config: {
type: 'line',
data: {
labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
datasets: [{
data: [
{x: 'a', y: 1},
{x: null, y: 1},
{x: 2, y: 1},
{x: undefined, y: 1},
{x: 4, y: 1},
{x: NaN, y: 1},
{x: 6, y: 1}
],
backgroundColor: 'red',
borderColor: 'red',
borderWidth: 5
}]
},
options: {
scales: {
y: {
display: false
},
x: {
grid: {
display: false
}
}
}
}
},
options: {
spriteText: true,
canvas: {
width: 256,
height: 256
}
}
};
Binary file added test/fixtures/scale.category/invalid-data.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 851861e

Please sign in to comment.