From 8ea9371421439a774d28d42bae8e406ce981a9c0 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Sat, 7 Jan 2023 17:17:20 -0800 Subject: [PATCH 1/2] solve 1427. Perform String Shifts --- 1427.perform-string-shifts.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 1427.perform-string-shifts.js 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 From 36e95c37ffb19c50c72c609735cc7bd82f1e0db3 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Sat, 7 Jan 2023 17:17:39 -0800 Subject: [PATCH 2/2] test function stringShift --- stringShift.test.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 stringShift.test.js 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