From e4dd158b241268600bb1c9005969af7b2efcb130 Mon Sep 17 00:00:00 2001 From: Ian Ker-Seymer Date: Tue, 26 Jul 2016 14:45:05 -0400 Subject: [PATCH] Fix out of bounds index access in getLabelMoment Previously, calling getLabelMoment with an out of bound index would cause an error such as this: ``` Uncaught TypeError: Cannot read property 'null' of undefined ``` This happens because there is not always guaranteed to be a labelMoment on at the current datasetIndex. One example of this is practice comes from a this function call: ```js // since the are not always guaranteed to be at least two labelMoments // \ / this index can be out of bounds // | var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6; ``` This patch simply ensures that the `labelMoments` for the `datasetIndex` are defined before accessing properties on it. --- src/scales/scale.time.js | 6 +++++- test/scale.time.tests.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/scales/scale.time.js b/src/scales/scale.time.js index c4099477823..91ac3aa0778 100755 --- a/src/scales/scale.time.js +++ b/src/scales/scale.time.js @@ -76,7 +76,11 @@ module.exports = function(Chart) { Chart.Scale.prototype.initialize.call(this); }, getLabelMoment: function(datasetIndex, index) { - return this.labelMoments[datasetIndex][index]; + if (typeof this.labelMoments[datasetIndex] != 'undefined') { + return this.labelMoments[datasetIndex][index]; + } + + return null; }, getMomentStartOf: function(tick) { var me = this; diff --git a/test/scale.time.tests.js b/test/scale.time.tests.js index f3173e1c455..88a21dda6c2 100755 --- a/test/scale.time.tests.js +++ b/test/scale.time.tests.js @@ -479,4 +479,33 @@ describe('Time scale tests', function() { threshold: 0.75 }); }); + + it("should not throw an error if the datasetIndex is out of bounds", function() { + var chart = window.acquireChart({ + type: 'line', + data: { + labels: ["2016-06-26"], + datasets: [{ + type: "line", + data: [5] + }] + }, + options: { + scales: { + xAxes: [{ + display: true, + type: "time", + }] + } + } + }); + + var xScale = chartInstance.scales.xScale0; + + var getOutOfBoundPixelForValue = function() { + xScale.getLabelMoment(12, 0); + }; + + expect(getOutOfBoundPixelForValue).not.toThrow(); + }); });