From fbf68e490f98735897b6ef28f047e1b259b40eab Mon Sep 17 00:00:00 2001 From: Walle Cyril Date: Sat, 22 Jun 2019 15:39:41 +0200 Subject: [PATCH 1/2] fix: return empty set when either is empty --- src/algorithms/sets/cartesian-product/cartesianProduct.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/algorithms/sets/cartesian-product/cartesianProduct.js b/src/algorithms/sets/cartesian-product/cartesianProduct.js index 14924fae..93f05f18 100644 --- a/src/algorithms/sets/cartesian-product/cartesianProduct.js +++ b/src/algorithms/sets/cartesian-product/cartesianProduct.js @@ -5,14 +5,17 @@ * @return {*[]} */ export default function cartesianProduct(setA, setB) { - // Check if input sets are not empty. + // Check if input sets are not non-arrays. // Otherwise return null since we can't generate Cartesian Product out of them. - if (!setA || !setB || !setA.length || !setB.length) { + if (!setA || !setB) { return null; } // Init product set. const product = []; + if (!setA.length || !setB.length) { + return product; + } // Now, let's go through all elements of a first and second set and form all possible pairs. for (let indexA = 0; indexA < setA.length; indexA += 1) { From ecdc7bd1723bd8f70764c5f1c19728b75c493405 Mon Sep 17 00:00:00 2001 From: Walle Cyril Date: Sat, 22 Jun 2019 17:01:03 +0200 Subject: [PATCH 2/2] test cartesian product --- .../cartesian-product/__test__/cartesianProduct.test.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/algorithms/sets/cartesian-product/__test__/cartesianProduct.test.js b/src/algorithms/sets/cartesian-product/__test__/cartesianProduct.test.js index f9154fa2..32ae3479 100644 --- a/src/algorithms/sets/cartesian-product/__test__/cartesianProduct.test.js +++ b/src/algorithms/sets/cartesian-product/__test__/cartesianProduct.test.js @@ -16,4 +16,12 @@ describe('cartesianProduct', () => { expect(product1).toEqual([[1, 1]]); expect(product2).toEqual([[1, 3], [1, 5], [2, 3], [2, 5]]); }); + + it('should return an empty set if one or both of the source is empty', () => { + const product1 = cartesianProduct([], [1, 2, 3]); + const product2 = cartesianProduct([], []); + + expect(product1).toEqual([]); + expect(product2).toEqual([]); + }); });