Skip to content

Commit a5e240f

Browse files
committed
Add unit tests for "find-2-nums-adding-to-n". Fix findTwoNumsAddingToN2 so it only returns one pair
1 parent dc22c0c commit a5e240f

File tree

3 files changed

+72
-15
lines changed

3 files changed

+72
-15
lines changed

package-lock.json

+30-11
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const { findTwoNumsAddingToN, findTwoNumsAddingToN2 } = require('.');
2+
3+
describe('Find two numbers adding to N', () => {
4+
[findTwoNumsAddingToN, findTwoNumsAddingToN2].forEach((func) => {
5+
describe(func.name, () => {
6+
it('Should return an array with length two', () => {
7+
expect(findTwoNumsAddingToN2([1, 2], 3).length).toBe(2);
8+
});
9+
10+
it('Should return false when there is no solution', () => {
11+
expect(findTwoNumsAddingToN2([1, 2], 5)).toBe(false);
12+
});
13+
14+
it('Should return false input array length is less than 2', () => {
15+
expect(findTwoNumsAddingToN2([5], 5)).toBe(false);
16+
});
17+
18+
it('Should return negative values', () => {
19+
expect(findTwoNumsAddingToN2([-2, 1, 2, 6, 7], 5)).toEqual(expect.arrayContaining([-2, 7]));
20+
});
21+
22+
it('Should return two numbers that sum to N', () => {
23+
expect(findTwoNumsAddingToN([1, 2, 3, 5], 5)).toEqual(expect.arrayContaining([2, 3]));
24+
});
25+
});
26+
});
27+
28+
describe('function differences findTwoNumsAddingToN and findTwoNumsAddingToN2', () => {
29+
it('Should return different arrays', () => {
30+
expect(findTwoNumsAddingToN([1, 2, 3, 4], 5))
31+
.toEqual(expect.not.arrayContaining(findTwoNumsAddingToN2([1, 2, 3, 4], 5)));
32+
});
33+
});
34+
});

src/_Problems_/find-2-nums-adding-to-n/index.js

+8-4
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,19 @@ function findTwoNumsAddingToN(arr, number) {
1818

1919
// the Brute force approach
2020
function findTwoNumsAddingToN2(arr, number) {
21-
const pair = [];
21+
2222
for (let i = 0; i < arr.length; i += 1) {
2323
for (let j = i + 1; j < arr.length; j += 1) {
2424
if (arr[i] + arr[j] === number) {
25-
pair.push(arr[i], arr[j]);
26-
break;
25+
return [arr[i], arr[j]];
2726
}
2827
}
2928
}
3029

31-
return pair.length ? pair : false;
30+
return false;
3231
}
32+
33+
module.exports = {
34+
findTwoNumsAddingToN,
35+
findTwoNumsAddingToN2,
36+
};

0 commit comments

Comments
 (0)