From 6c35f8bc6abdd7a90ae88f076f417f3f44ce16c2 Mon Sep 17 00:00:00 2001 From: Luiz Date: Mon, 16 May 2022 19:28:08 -0300 Subject: [PATCH] Add check to non existing row key when getting aggregator --- src/Utilities.js | 2 +- src/__tests__/Utilities-test.js | 34 ++++++++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/Utilities.js b/src/Utilities.js index 15dfac4..dc5c7e0 100644 --- a/src/Utilities.js +++ b/src/Utilities.js @@ -705,7 +705,7 @@ class PivotData { } else if (colKey.length === 0) { agg = this.rowTotals[flatRowKey]; } else { - agg = this.tree[flatRowKey][flatColKey]; + agg = (this.tree[flatRowKey] || {})[flatColKey]; } return ( agg || { diff --git a/src/__tests__/Utilities-test.js b/src/__tests__/Utilities-test.js index d7f41bd..27bf3c2 100644 --- a/src/__tests__/Utilities-test.js +++ b/src/__tests__/Utilities-test.js @@ -19,7 +19,11 @@ const fixtureData = [ describe(' utils', function() { describe('.PivotData()', function() { describe('with no options', function() { - const aoaInput = [['a', 'b'], [1, 2], [3, 4]]; + const aoaInput = [ + ['a', 'b'], + [1, 2], + [3, 4], + ]; const pd = new utils.PivotData({data: aoaInput}); it('has the correct grand total value', () => @@ -27,7 +31,11 @@ describe(' utils', function() { }); describe('with array-of-array input', function() { - const aoaInput = [['a', 'b'], [1, 2], [3, 4]]; + const aoaInput = [ + ['a', 'b'], + [1, 2], + [3, 4], + ]; const pd = new utils.PivotData({ data: aoaInput, aggregatorName: 'Sum over Sum', @@ -39,7 +47,10 @@ describe(' utils', function() { }); describe('with array-of-object input', function() { - const aosInput = [{a: 1, b: 2}, {a: 3, b: 4}]; + const aosInput = [ + {a: 1, b: 2}, + {a: 3, b: 4}, + ]; const pd = new utils.PivotData({ data: aosInput, aggregatorName: 'Sum over Sum', @@ -129,6 +140,23 @@ describe(' utils', function() { expect(agg.format(val)).toBe('1'); }); + it('returns empty aggregator when key not found', function() { + // inexistent row key, empty col key + let agg = pd.getAggregator(['x', 'y'], []); + let val = agg.value(); + expect(val).toBe(null); + + // empty row key, inexistent col key + agg = pd.getAggregator([], [1, 2]); + val = agg.value(); + expect(val).toBe(null); + + // inexistent row key, non empty col key + agg = pd.getAggregator(['x', 'y'], [1, 2]); + val = agg.value(); + expect(val).toBe(null); + }); + it('has a correct grand total aggregator', function() { const agg = pd.getAggregator([], []); const val = agg.value();