C
C
campus12018-03-15 19:42:42
JavaScript
campus1, 2018-03-15 19:42:42

How to solve a problem with codewars?

Hello guys. There is a task to find the first not the repetition. letter in a string.
I did so.

const firstNonRepeatingLetter = str => {
  let charMap = {};
  let strToLower = str.toLowerCase();
  for (let char of strToLower) {
    if (!charMap[char]) {
      charMap[char] = 1;
    } else {
      charMap[char]++;
    }
  }

  for (let char in charMap) {
    if (charMap[char] === 1) {
      return char;
    }
  }
  return '';
};

But 1 test does not pass, because "T" is passed to the input sTreSSand should return "T", and I have "t". Tell me what needs to be fixed?
Task
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2018-03-15
@campus1

Well, if not rewriting the code, but adding something like this

const firstNonRepeatingLetter = str => {
  let charMap = {};
  let strToLower = str.toLowerCase();
  for (let char of strToLower) {
    if (!charMap[char]) {
      charMap[char] = 1;
    } else {
      charMap[char]++;
    }
  }

  for (let char in charMap) {
    if (charMap[char] === 1) {
      var i = str.indexOf(char);
      if( i == -1)
        i = str.indexOf(char.toUpperCase())
      else if(str.indexOf(char.toUpperCase()) != -1 && str.indexOf(char.toUpperCase()) < i)
        i = str.indexOf(char.toUpperCase());
      return str.charAt(i);
    }
  }
  return '';
};

PS In general, you can make it a little shorter
function firstNonRepeatingLetter(str) {
  for(var i = 0 ; i < str.length;i++)
  if((str.substring(0,i)+str.substring(i+1)).indexOf(str.charAt(i).toLowerCase()) == -1 && (str.substring(0,i)+ str.substring(i+1)).indexOf(str.charAt(i).toUpperCase()) == -1)
      return str.charAt(i);
  return '';
}

Although I'm sure it can be even shorter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question