diff --git a/1427.perform-string-shifts.js b/1427.perform-string-shifts.js new file mode 100644 index 00000000..a6c81681 --- /dev/null +++ b/1427.perform-string-shifts.js @@ -0,0 +1,30 @@ +/* URL of this problem + * https://leetcode.com/problems/perform-string-shifts/description/ + * + * @param {string} s + * @param {number[][]} shift + * @return {string} + */ + +var stringShift = function(s, shift) { + const Shifted = [...s]; + + for (let i = 0; i < shift.length; i++) { + const ShiftAmount = shift[i][1]; + + // 0 means left shift and 1 for right shift for shift[1][0] + if (shift[i][0] === 0) { + for (let j = 0; j < ShiftAmount; j++) { + Shifted.push(Shifted.shift()); + } + } else { + for (let j = 0; j < ShiftAmount; j++) { + Shifted.unshift(Shifted.pop()); + } + } + } + + return Shifted.join(""); +}; + +module.exports = stringShift; \ No newline at end of file diff --git a/stringShift.test.js b/stringShift.test.js new file mode 100644 index 00000000..0fe250ce --- /dev/null +++ b/stringShift.test.js @@ -0,0 +1,17 @@ +const stringShift = require("./1427.perform-string-shifts"); + +test("Return the final string after the shift operations", () => { + expect(stringShift("abcdefg", [[1,1],[1,1],[0,2],[1,3]])).toBe("efgabcd"); +}); + +test("Return an empty string if the input string is empty", () => { + expect(stringShift("", [[1,1],[1,1],[0,2],[1,3]])).toBe(""); +}); + +test("Return the original string if the input shift has no element", () => { + expect(stringShift("abcdefg", [])).toBe("abcdefg"); +}); + +test("Return the original string if all of the shift amounts are 0", () => { + expect(stringShift("abcdefg", [[1,0],[0,0],[0,0],[1,0]])).toBe("abcdefg"); +}); \ No newline at end of file