Skip to content

Commit 6fff99d

Browse files
committed
Added cartesianProduct.js
1 parent e9b8b13 commit 6fff99d

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Maths/CartesianProduct.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @function cartesianProduct
3+
* @description Generate Cartesian Product of Two Sets.
4+
* @param {*[]} setA -First set
5+
* @param {*[]} setB -Second set
6+
* @return {*[]} -Cartesian Product of setA and setB
7+
*/
8+
const cartesianProduct = (setA, setB) => {
9+
// Check if input sets are not empty.
10+
if (!setA || !setB || !setA.length || !setB.length) {
11+
return null;
12+
}
13+
const product = [];
14+
15+
for (let indexA = 0; indexA < setA.length; indexA += 1) {
16+
for (let indexB = 0; indexB < setB.length; indexB += 1) {
17+
product.push([setA[indexA], setB[indexB]]);
18+
}
19+
}
20+
21+
return product
22+
}
23+
24+
export { cartesianProduct }

Maths/test/CartesianProduct.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import {cartesianProduct} from '../cartesianProduct';
2+
3+
describe('cartesianProduct', () => {
4+
it('should return null if not enough info for calculation', () => {
5+
const product1 = cartesianProduct([1], null)
6+
const product2 = cartesianProduct([], null)
7+
8+
expect(product1).toBeNull()
9+
expect(product2).toBeNull()
10+
})
11+
12+
it('should calculate the product of two sets', () => {
13+
const product1 = cartesianProduct([1], [1])
14+
const product2 = cartesianProduct([1, 2], [3, 5])
15+
16+
expect(product1).toEqual([[1, 1]]);
17+
expect(product2).toEqual([[1, 3], [1, 5], [2, 3], [2, 5]])
18+
})
19+
})

0 commit comments

Comments
 (0)