function hasDuplicate(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) {
return false;
}
seen.add(n);
}
return true;
}
console.log(hasDuplicate([2, 7, 4, 7]));
Reply with what is broken and how you would fix it.
Your return values are flipped relative to the function name/intent. Right now it returns false when it finds a duplicate, and true when it gets through the loop without finding one. Fix it by returning true on the duplicate branch and false at the end:
function hasDuplicate(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) {
return true;
}
seen.add(n);
}
return false;
}
console.log(hasDuplicate([2, 7, 4, 7])); // true