Initially, I was tasked with creating a function that could either append the first color in an array to the end or reverse the order of colors. This is the function I created:
// Obtain the colors from scope
var colours = scope.colours;
// Create the swap function
scope.swap = function (opposite) {
// If we want to reverse the order
if (opposite) {
// Reverse the array
colours.unshift(colours.pop());
// Else
} else {
// Shift the array
colours.push(colours.shift());
}
};
Everything was working fine until my client presented me with a more complex challenge and I am wondering if there is an easy way to achieve this.
The client provided a table resembling this:
| C1 | C2 | C3 |
| C2 | C1 | C3 |
| C1 | C3 | C2 |
| C2 | C3 | C1 |
The requirement is:
- C3 can only be in positions 2 and 3
- C2 and C1 can occupy any position
Before diving into it, does anyone have suggestions for simplifying this?
Potential Solution
Despite considering other alternatives, I decided to attempt solving it myself. Here's what I came up with:
// Get the colors from scope
var colours = scope.colours;
// Define variables
counter = 2;
// Create the swap function
scope.swap = function (opposite) {
switch (counter) {
case 3:
// Retrieve colors
var colour2 = colours.shift();
var colour3 = colours.shift();
// Rearrange them
colours.splice(1, 0, colour2);
colours.splice(2, 0, colour3);
break;
case 1:
// Retrieve colors
var colour2 = colours.shift();
var colour1 = colours.shift();
// Rearrange them
colours.splice(0, 0, colour1);
colours.splice(2, 0, colour2);
break;
case 0:
// Retrieve colors
var colour1 = colours.shift();
var colour3 = colours.shift();
// Rearrange them
colours.splice(1, 0, colour3);
colours.splice(2, 0, colour1);
break;
default:
// Remove and store the first color value
var colour1 = colours.shift();
// Add the color to the second position in the array
colours.splice(1, 0, colour1);
break;
}
counter--;
if (counter < 0) {
counter = 3;
}
};
This approach functions well, but how can I extend it to work in the opposite direction? For instance, increasing the counter rather than decreasing it (and resetting to 0 when exceeding 3).