เราต้องเขียนฟังก์ชันเลื่อนสตริงแบบวนรอบ (circular shift) โดยระบุจำนวนครั้งที่เลื่อนซ้าย (leftShifts) และขวา (rightShifts)
Left Shift: ตัวอักษรแรกไปเป็นตัวสุดท้าย, Right Shift: ตัวอักษรสุดท้ายไปเป็นตัวแรก
ตัวอย่างโค้ด
const str = 'abcdef';
const getShiftedString = (str, leftShifts, rightShifts) => shiftByAmount(shiftByAmount(str, leftShifts), -rightShifts);
const shiftByAmount = (str, leftShifts) => {
leftShifts = leftShifts % str.length;
return str.slice(leftShifts) + str.slice(0, leftShifts);
};
console.log(getShiftedString(str, 3, 2));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
bcdefa