Im trying to solve this kata: https://www.codewars.com/kata/63f96036b15a210058300ca9/train/javascript
"In this kata, you need to write a function that takes a string and a letter as input and then returns the index of the second occurrence of that letter in the string. If there is no such letter in the string, then the function should return -1. If the letter occurs only once in the string, then -1 should also be returned."
Im useing ASCII code to to convert letters in order to distinguish capital and small letters. But i get problem with random tests. I have no idea what im doing wrong...
const secondSymbol = (str, symbol) => {
console.log(str, symbol);
let symbolAscii = symbol.charCodeAt(0);
const strArrAscii = str.split('').map(ele => ele.charCodeAt());
if (strArrAscii.indexOf(symbolAscii) === -1) return -1;
else if ((strArrAscii.indexOf(symbolAscii) !== strArrAscii.lastIndexOf(symbolAscii)))
{
strArrAscii[strArrAscii.indexOf(symbolAscii)] = '=';
return strArrAscii.indexOf(symbolAscii);
}
else return strArrAscii.indexOf(symbolAscii);
}
secondSymbol('CQigLHAAxTuCezwqbqMeGOnECbSyLdNfYUxqkLAUvPZzSFbhTfwSVGWzuqvotdOjRxksLRIAQQvogvUmYAr p
fYSbpOOLcxuzD', 'L');
The problem is in your final else
block. This deals with the case when there is only one occurrence of the letter. The challenge explains that you should return -1 in that case, yet you return the index of that character.
So change that final else
from this:
else return strArrAscii.indexOf(symbolAscii);
to this:
else return -1;
There is no need to convert characters to their numerical code. In JavaScript you can compare characters without any need of conversion.
There is no need to create an array from your string (using split("")
). You can get the index of a character by directly calling indexOf
on the string.
You can make use of the second argument of the indexOf
method, which is useful to find the second occurrence.
Like this:
const secondSymbol = (str, symbol) => {
let i = str.indexOf(symbol);
if (i >= 0) i = str.indexOf(symbol, i + 1);
return i;
}