Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
i need to find the distance between two characters in string js. i have a solution but i can't understand the snippet of code related to if statement

The task was to write a function subLength() that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.

const subLength = (str, char) => {
let charCount = 0;
let len = -1;

for (let i=0; i<str.length; i++) {
  if (str[i] == char) {
    charCount++;
    if (charCount > 2) {
      return 0;
    }
// could somebody explain why -1 is equal to len and then len is reassigned to i???       
if (len == -1) {
      len = i;
    } else {
      len = i - len + 1
    }
  }
}
if (charCount < 2) {
  return 0;
}

return len;
};

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

in the first occurrence len= -1 so: (len ==-1) turned to true; and len is changed to i so len=i; in the second occurance len is not -1 so:

len = i - len -1;

in essence, in the above expression, len keeps the index of the first occurrence, and i has the index of second occurrence, so the difference will be, the difference between two occurrences, 'qweraq' : first occurrance: 0, second: 6. 6-0-1= 5 is difference;

about 4 years ago · Juan Pablo Isaza Relatório

0

This is how I manage to rewrite your code. Hope this helps.

const subLength = (str, char) => {
  const arr = str.split('');
  let count = 0;
  arr.forEach(letter => letter === char ? count++ : '')
  const result = arr.some(letter => {
    if (arr.indexOf(char) !== arr.lastIndexOf(char) && count == 2) {
      return true
    }
    return false
  })
  return result ? Math.abs(arr.indexOf(char) - arr.lastIndexOf(char)) + 1 : 0
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Whilst its possible to calculate the indexes and the count within a single loop, given the triviality I'd favor standard API methods for scanning. one could always optimize later if the application actually called for it.

First we convert the string to an array so that we have the ability to filter for matches to the input character, and derive the length.

Only if there are 2 occurrences do we calculate the distance between using the indexOf and lastIndexOf methods on string (note that these will only require a second full scan of the string if the two occurrences are consecutive).

Otherwise, the result should be 0.

const subLength = (str, chr) => {

    const count = str.split('').filter(ltr => ltr === chr).length
    if (count === 2) {
        return (str.lastIndexOf(chr) - str.indexOf(chr)) + 1
    }
    return 0
}


console.log(subLength('asddfghvcba', 'a'))
console.log(subLength('asddfghvcba', 'x'))
console.log(subLength('aaaaaaaaaaa', 'a'))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda