Skip to content

Instantly share code, notes, and snippets.

@dmmulroy
Created January 24, 2018 14:00
Show Gist options
  • Save dmmulroy/9eb05c6eefd92cb2e41f89ef116c328a to your computer and use it in GitHub Desktop.
Save dmmulroy/9eb05c6eefd92cb2e41f89ef116c328a to your computer and use it in GitHub Desktop.
All Tests Pass: Week 1
/**
* All Tests Pass: Week 1
* Given an array of integers, find out if any two items in the array add up to
* the target. For example, sumsToTarget([1,2], 3) should return true, but
* sumsToTarget([1,2], 4) should return false.
*/
function sumsToTarget(integers = [], target) {
const uniqueIntegers = new Set(integers);
for (const integer of uniqueIntegers) {
const difference = target - integer;
if (uniqueIntegers.has(difference)) return true;
}
return false;
}
// Tests: Don't edit anything after this line.
assertEqual(sumsToTarget([1, 5, 3], 3), false, "Array [1, 5, 3] does not have items that add up to 3");
assertEqual(sumsToTarget([0, 2, 3, 5, 8], 3), true, "Array [0, 2, 3, 5, 8] has items that add up to 3");
assertEqual(sumsToTarget([5, 5], 5), false, "[5, 5] does not have items that add up to 5");
console.log("All clear 🎉");
function assertEqual(first, second, output) {
try {
if (first !== second) {
throw `${output} ${first} ${second}`
}
} catch (e) {
throw `${e} - ${output} ${first} ${second}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment