Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda