Search code examples
javascriptarrays

Relative-shift an element with rotation in an array


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const output = move(numbers, 3, -5);

console.log(output);

function move(array, index, offset) {
    const output = [...array];
    const element = output.splice(index, 1)[0];
    output.splice(index + offset, 0, element)
    return output;
}

The first line is an array of numbers.

At the second line, when calling the move function, we pass three arguments.

First, is the array itself called numbers. Secondly, the index of the number we are trying to move (in the example, we have index 3 so we are passing the number 4). Finally, we have the offset set to -5. The negative sign means we are moving the number to the left. The 5 means 5 positions.

But as you can see, we only have 3 positions to the left of the number 4 before reaching the beginning of the array. In this case, we have to go to the end of the array and count backwards. So, we are looking for a function which will turn the original array to [1, 2, 3, 5, 6, 7, 8, 4, 9]. As you can see, number 4 has shifted 3 positions to the left to reach the beginning of the array, then, 2 further positions from the end of the array.

A further example to clarify.

Let's say we write:

const output = move(numbers, 1, -4);  

In this example, we want the number 2 from the array (index 1) to move 4 positions to the left. So, we should get [1, 3, 4, 5, 6, 7, 2, 8, 9].


Solution

  • You need to cover the edge cases when the updated index is less than 0 OR greater than the array length. You can try following

    const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    function move(array, index, offset) {
        const output = [...array];
        const element = output.splice(index, 1)[0];
        let updatedIndex = index + offset;
        if(updatedIndex < 0) updatedIndex++; 
        else if (updatedIndex >= array.length) updatedIndex -= array.length;
        output.splice(updatedIndex, 0, element);
        return output;
    }
    
    console.log(move(numbers, 3, -5));