mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Merge ecdc7bd172
into ca3d16dcce
This commit is contained in:
commit
c082a7052d
@ -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([]);
|
||||
});
|
||||
});
|
||||
|
@ -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) {
|
||||
|
Loading…
Reference in New Issue
Block a user