You're a magician and you handle a deck of cards. You can already move a card from one position to another position within a deck. In order to correctly execute your magic trick, you need to be able to perform a sequence of moves. You already have two functions named arrange and rearrange which perform a single move, in either direction.
Your task is to extend the existing code with new functionality to perform a sequence of moves. The new implementation should:
- execute a single move when given
fromandtoas numbers. - execute a sequence of moves when given an array of number pairs.
Extend function arrange that takes:
- an
array(of lengthn) of items, - a
fromposition (wholenumber,-n <= from < n), - and
toposition (wholenumber,-n <= to < n)
so that it can also take
- an
array(of lengthn) of items, - an
arrayof position (wholenumber,-n <= from < n) pairs in the form[from, to],
As in the existing code, positive numbers mean that you move cards from the bottom of the deck (the left hand side) and negative numbers refer to starting at the top of the deck (the right hand side).
It returns a new array with the item moved from the position from to the position to:
const before = ["❤ A", "❤ 9", "❤ 3", "❤ 6", "♣ A"];
const magics = arrange(before, [[1, -2]]);
magics;
// => ['❤ A', '❤ 3', '❤ 6', '❤ 9', '♣ A']
// ^--- has moved from position 1 to -2 (from the right side)Extend the second function rearrange to do the same thing, but mutate the original input array:
const before = ["❤ A", "❤ 3", "❤ 6", "❤ 9", "♣ A"];
const magics = rearrange(before, [[4, 0]]);
magics;
// => ['♣ A', '❤ A', '❤ 3', '❤ 6', '❤ 9']
// ^--- has moved from position 4 to 0
magics === before;
// => true