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

133
Visualizações
Javascript Algorithm - If the subtraction of indices is negative, return as elements of array as possible

Imagine a list of items:

const data = [0, 1, 2, 3, 4, 5]

One variable represents the main item:

const initialIndex = 1;

And the other variable, the number of extra elements that will also be collected behind of the "main item".

const extraCount = 2;

So, if for example, I call the method "algorithm" as follows:

function algorithm(data, initialIndex, extraCount) { ... }


console.log(algorithm(data, 2, 1));

It will return me [1, 2] // The initial index and the first element behind it

Or, if for example I call again with

console.log(algorithm(data, 4, 3));

It will return me [1, 2, 3, 4] // The initial element and 3 items behind it

How can I do, in a simple way, to fix this use case

 console.log(algorithm(data, 1, 2)); // Negative index...

But... I need to return at least the possible items.

I mean:

For console.log(algorithm(data, 1, 2)); I get [0, 1] // Initial index, and the first item before (not two because the second one has a negative index)

For console.log(algorithm(data, 2, 5)); I get [0, 1, 2]

For console.log(algorithm(data, 0, 10)); I get [0]

For console.log(algorithm(data, 3, 7)); I get [0, 1, 2, 3]

EDIT

This is what I have tried

const data = [0, 1, 2, 3, 4];
const initialIndex = 2;
const extraCount = 2;
    
const start = initialIndex - extraCount >= 0 ? initialIndex - extraCount : initialIndex;

const end = initialIndex + 1;

console.log(data.slice(start, end));

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

0

You have it correct. Just replace initialIndex by 0 in else condition

const data = [0, 1, 2, 3, 4];

let func = (initialIndex,extraCount) => {
    
const start = initialIndex - extraCount >= 0 ? initialIndex - extraCount : 0;

const end = initialIndex + 1;

console.log(data.slice(start, end));

};

func(2,2);
func(1,2);
func(3,7);

Note: There are a lot of other ways to do it, but this is the one you were going for so I just pointed out the issue

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use slice(-count) to return elements from the end of array, something like this:

if (extraCount > initialIndex) {
  return [
    // This will return elemnts from beginning of array up to initialIndex
    ...data.slice(0, initialIndex),

    // This will return the missing elements looped from the other side of array
    ...data.slice(extraCount - initialIndex)
  ];
}

You should also incorporate other sanity checks into your code, or example, total number of elements should not exceed array length, etc.

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