Exploring Sets in Javascript

The Problem

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Examples

My Thought Process Before Sets

Prior to encountering Javascript Sets, I’d have gone about this problem by:

Here’s a valid implementation of what this idea would look like:

function duplicateCount(text) {
  const tracker = {};
  const dupes = [];

  for (const char of text.toLowerCase()) {
    if (tracker.hasOwnProperty(char)) {
      tracker[char]++;
    } else {
      tracker[char] = 1;
    }
  }

  for (const prop in tracker) {
    if (tracker[prop] > 1) dupes.push(prop);
  }

  return dupes.length;
}

My Thought Process After Sets

However, since learning that “the Set object lets one store unique values of any type”, this is how I went about the challenge.

Here’s a working implementation of this idea:

function duplicateCount(text) {
  if (!text) return 0; // no need moving forward if input is empty

  const tracker = new Set(); // keep track of all characters in the input
  const dupes = new Set(); // keep track of duplicate characters

  for (const char of text.toLowerCase()) {
    if (tracker.has(char)) {
      dupes.add(char);
    } else {
      tracker.add(char);
    }
  }

  return dupes.size;
}

Refs: