How to determine if a string is a rotation of another in JavaScript

Here is one way to determine whether a string is a rotation of another string in JavaScript.
Space complexity: O(n)
Time complexity: O(n)

isRotationTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Determine whether one String
// is a rotation of another String
// by calling isSubstring only once
function isRotation(s1, s2) {
const s3 = s1 + s1;
return typeof s1 === 'string' && typeof s2 === 'string' && s1.length === s2.length && isSubstring(s3, s2);
}
function isSubstring(s1, s2) {
return s1.indexOf(s2) !== -1;
}
// ==== Tests
function runTests(func) {
const inputOutput = [['foobarbaz', 'barbazfoo', true], ['', '', true], ['foo', '', false], ['', 'foo', false], [null, 'foo', false]];
for (let i = 0; i < inputOutput.length; i++) {
const input = inputOutput[i].slice(0, inputOutput[i].length-1);
const expected = inputOutput[i][inputOutput[i].length-1];
const result = func(...input);
if (result !== expected) {
return `Test failed: Expected - ${expected}. Got ${result}`;
}
}
return 'All tests passed!'
}
runTests(isRotation); // All tests passed
// Test cases
// isRotation('foobarbaz', 'barbazfoo'); // true
// isRotation('', ''); // true
// isRotation('foo', '') // false
// isRotation('', 'foo') // false
// isRotation(null, 'foo') // false