The task:
Given two strings A and B, return whether or not A can be shifted some number of times to get B.
For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false.
Solution 1:
const haveSameLength = (a, b) => a.length === b.length;
const isSame = (a, b) => a === b;
const isFullyShifted = a => a === 0;
const shiftStringBy = i => a => `${a.substring(i)}${a.substring(0, i)}`;
const isSameAfterShifting = (strA, strB, items) => {
if (strA.length === 0 || strB.length ===0) { return false }
if (!haveSameLength(strA, strB)) { return false }
if (isSame(strA, strB)) { return true }
if (isFullyShifted(items)) { return false }
return isSameAfterShifting(strA, shiftStringBy(1)(strB), --items)
}
const str1 = 'abcde';
const str2 = 'cdeab';
console.log(isSameAfterShifting(str1, str2, str2.length));
Solution 2
const isSameAfterShifting2 = (strA, strB) => {
if (strA.length === 0 || strB.length ===0) { return false }
if (!haveSameLength(strA, strB)) { return false }
const arrB = strB.split('');
const firstLetterA = strA.substring(0, 1);
let shiftIndex = arrB.indexOf(firstLetterA);
if (shiftIndex === -1) { return false }
while (shiftIndex < arrB.length) {
const strBShifted = `${strB.substring(shiftIndex)}${strB.substring(0, shiftIndex)}`;
if (strA === strBShifted) { return true }
shiftIndex++;
}
return false;
}
console.log(isSameAfterShifting2('abc', 'acb'));
Which one is more readable and easier to understand for you?
const isShifted = (a, b) => a.length === b.length && a === b || (a + a).includes(b);
\$\endgroup\$