Home > database >  Javascript Algorithm - If the subtraction of indices is negative, return as elements of array as pos
Javascript Algorithm - If the subtraction of indices is negative, return as elements of array as pos

Time:10-18

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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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.

  • Related