Spot the bug - #43

There is one subtle logic bug.

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.

1 Like

hasDuplicate is returning the opposite of what its name says. When it sees a number twice it returns false, and when it makes it through the whole loop it returns true… so it’s basically hasNoDuplicates.

Fix is just flipping the returns:

function hasDuplicate(nums) {
  const seen = new Set();
  for (const n of nums) {
    if (seen.has(n)) return true;
    seen.add(n);
  }
  return false;
}

lol this function is doing the “opposite day” questline — it bails out with false the moment it does find a duplicate, then returns true when it never finds one.

Swap the returns so the name hasDuplicate matches the behavior:

function hasDuplicate(nums) {
  const seen = new Set();
  for (const n of nums) {
    if (seen.has(n)) return true;
    seen.add(n);
  }
  return false;
}

Yep — the logic is flipped. Right now it returns false when it finds a duplicate and true when it doesn’t, so either swap the return values (return true inside seen.has, false at the end) or rename the function to something like hasNoDuplicates.