I needed to write a function in JavaScript which checks if any rotation of an array is equal to another array.
By rotation, I mean:
rotate [1, 2, 3] --> [3, 1, 2]
rotate [3, 1, 2] --> [2, 3, 1]
rotate [2, 3, 1] --> [1, 2, 3]
Here's the code for my function. It feels pretty verbose, especially since the array functions added by ES6 seem perfect for this sort of thing, yet I've used very few of them. In particular, using a label on the outer loop feels wrong.
Is there any way I can make this function shorter and/or faster?
/**
* Taking two arrays, checks whether one may be rotated so that it equals
* the other.
*/
function arraysEqualByRotation(first, second) {
if (first.length !== second.length) {
return false;
}
// We'll rotate the first continually and compare it to the second
var rotatedFirst = first.slice(0);
outer:
for (var rotateCounter = 0; rotateCounter < rotatedFirst.length; rotateCounter++) {
// Rotate the array
rotatedFirst.unshift(rotatedFirst.pop());
// Check if their elements are equal
for (var i = 0; i < rotatedFirst.length; i++) {
if (rotatedFirst[i] !== second[i]) {
// Try another rotation
continue outer;
}
}
// At this stage, they're equal
return true;
}
// At this stage, a matching combination was never found
return false;
}
Example inputs and outputs:
first | second | result
-----------------------------------------------
[1, 2, 3] | [1, 2, 3] | true (same array)
[1, 2, 3] | [3, 1, 2] | true (rotate once)
[1, 2, 3] | [2, 3, 1] | true (rotate twice)
[1, 2] | [1, 2, 3] | false (different lengths)
[1, 2, 3] | [1, 3, 2] | false (no valid rotation)