function twoSum(nums, target) {
const values = nums.reduce((map, num, index) => {
map[num] = index;
return map;
}, {});
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (values[target-num] !== undefined) {
return [values[num],values[target-num]];
}
}
return null;
}
function runTests(func) {
const inputOutput = [[[1, 3, 2, -7, 5], 7, [2, 4]]];;
for (let i = 0; i < inputOutput.length; i++) {
const input = inputOutput[i].slice(0, inputOutput[i].length-1);
const expected = inputOutput[i][inputOutput[i].length-1];
const result = func(...input);
if (!deepEquals(result, expected)) {
return `Test failed: Expected - ${expected}. Got ${result}`;
}
}
return 'All tests passed!'
}
function deepEquals(x, y) {
if ((typeof x === "object" && x !== null) && (typeof y === "object" && y !== null)) {
if (Object.keys(x).length != Object.keys(y).length)
return false;
for (var prop in x) {
if (y.hasOwnProperty(prop))
{
if (!deepEquals(x[prop], y[prop]))
return false;
}
else
return false;
}
return true;
}
else if (x !== y)
return false;
else
return true;
}
runTests(twoSum);