Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Returns true if any two numbers in given array add up to given integer. This was a "live" coding question I was given in an interview.
/**
* Returns true if any two numbers in list add up to num
*/
function sumTwoMatch(list, num) {
var i = 0,
match = false,
list2;
for (; i < list.length; i++) {
list2 = list.slice();
list2.splice(i, 1);
match = list2.some(function(val) {
return (list[i] + val === num);
});
if (match) {
return true;
}
}
return false;
}
// Tests
console.log(
sumTwoMatch([1, 5, 3, 4, 5], 10), // true
sumTwoMatch([1, 5, 3, 4, 5], 11), // false
sumTwoMatch([1, 5, 3, 4, 5], 8), // true
sumTwoMatch([1, 5, 3, 4, 5], 3), // false
sumTwoMatch([1, 5, 3, 4, 5], 5), // true
sumTwoMatch([1, 5, 3, 4, 5], 3), // false
sumTwoMatch([1, 5, 3, 4, 5], 9), // true
sumTwoMatch([1, 5, 3, 4, 5], 2) // false
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment