HappyHands31
HappyHands31

Reputation: 4101

Why Is Empty Argument Not Getting Identified as Undefined?

I have an (almost) working solution for a coding challenge:

function addLetters(...letters) {
  let sum = 0;
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
  if (typeof letters === 'undefined' || letters === [] || letters === undefined) {
    return 'z';
  }
  for (let i = 0; i < letters.length; i++) {
    sum += (alphabet.indexOf(letters[i]) + 1);
  }
  if (sum <= 26) {
    return alphabet[sum - 1];
  } else {
    while (sum > 26) {
      sum = (sum - 26);
      if (sum <= 26) {
        return alphabet[sum - 1];
      }
    }
  }
}

console.log(addLetters())

But as you can see, in this particular case of console.log(addLetters()), it's returning undefined instead of 'z' - why is that?

I think it must have something to do with the way that ...letters is a rest / default / destructured / spread argument.

The challenge does, in fact, want the argument to appear as a spread, but I don't know how to accommodate for it.

EDIT Test specs for challenge:

enter image description here

Upvotes: 1

Views: 56

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

letters  === []

Will always be false, as these are two different references which will never evaluate to true, you need to check the length of array to check if it's empty or not

Also you can safely remove the other two conditions from if statement as letters will always be an array

function addLetters(...letters) {
  let sum = 0;
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
  if (letters.length === 0) {
    return 'z';
  }
  for (let i = 0; i < letters.length; i++) {
    sum += (alphabet.indexOf(letters[i]) + 1);
  }
  if (sum <= 26) {
    return alphabet[sum - 1];
  } else {
    while (sum > 26) {
      sum = (sum - 26);
      if (sum <= 26) {
        return alphabet[sum - 1];
      }
    }
  }
}

console.log(addLetters())

Upvotes: 3

Amardeep Singh
Amardeep Singh

Reputation: 413

Try this. :)

function addLetters(...letters) {
  let sum = 0;
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
  if (!letters.length) {
    return 'z';
  }
  for (let i = 0; i < letters.length; i++) {
    sum += (alphabet.indexOf(letters[i]) + 1);
  }
  if (sum <= 26) {
    return alphabet[sum - 1];
  } else {
    while (sum > 26) {
      sum = (sum - 26);
      if (sum <= 26) {
        return alphabet[sum - 1];
      }
    }
  }
}

Upvotes: 1

Related Questions