Hello World Master

Tutorials, articles and quizzes on Software Development

Algorithms > Articles

Unique Email Addresses problem in Javascript

I recently completed the Leetcode challenge: Unique email addresses.

The issue is this, the localname (anything left of the @ sign in an email) may follow a certain set of rules if it contains a ‘+’ or a ‘.’

If the email address contains an ‘.’ we just ignore it and act as if it was never there. So cat.food@meow.com or even ca.t.foo.d@meow is the same as catfood@meow.com.

If our email address contains a ‘+’. we ignore everything on the right side up until the ‘@’ sign in the email. So if our dog+food@woof.com would just be dog@woof.com. Keep in mind if theres a period anywhere after the plus sign it wont apply to the final email address we sent and we get rid of it like any other character after + and before @.

rabbit+baby.food@hop.com would just be rabbit@hop.com

The leetcode questions give us an array of email addresses and we have to determine how many addresses total are sent an email. This implies that after following the rules that come with having a ‘+’ or ‘.’ in the email, some of these email addresses are duplicates.

Using my knowledge of Javascript, I created an array to hold the final email addresses, use the split() function to split up the email addresses by either ‘+’ or ‘.’

If i was dealing with a ‘+’ i would only bring back the substring in the 0 index of my resulting array

However, if I was dealing with a ‘.’ i would join all the values in the array, which results in a string containing no periods.

I would also split the values adjacent to ‘@’ to get the domain name by itself, and then create a new string by concatenating an ‘@’ symbol and the index 1 of my split array.

My final result was this:

var numUniqueEmails = function(emails) {
    var address = new Set();
    for(email of emails) {
      var domain;
      var getAt = email.split('@');
      domain = '@' + getAt[1];
      
      var localname;
      var getLocalName = getAt[0].split('+');
      localname = getLocalName[0];
      var removePeriod = localname.split('.').join('');
      var total = removePeriod+domain;
      console.log(total)
      if(!address.has(total)){
        address.add(total);
      }
    }
  return address.size
};