diff --git a/2138.divide-a-string-into-groups-of-size-k.js b/2138.divide-a-string-into-groups-of-size-k.js new file mode 100644 index 00000000..376070a9 --- /dev/null +++ b/2138.divide-a-string-into-groups-of-size-k.js @@ -0,0 +1,28 @@ +/* URL of this problem + * https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/description/ + * + * @param {string} s + * @param {number} k + * @param {character} fill + * @return {string[]} + */ + +var divideString = function(s, k, fill) { + const Divided = []; + const LastGroupLen = s.length % k; + + for (let i = 0; i < s.length; i += k) { + const Substr = s.substring(i, i + k); + + Divided.push(Substr); + } + // A character fill is used to complete the group + // if the length of the last group does not have k characters remaining. + if (LastGroupLen > 0 && LastGroupLen < k) { + Divided[Divided.length -1] += fill.repeat(k - LastGroupLen); + } + + return Divided; +}; + +module.exports = divideString; \ No newline at end of file diff --git a/divideString.test.js b/divideString.test.js new file mode 100644 index 00000000..106ddbe1 --- /dev/null +++ b/divideString.test.js @@ -0,0 +1,13 @@ +const divideString = require("./2138.divide-a-string-into-groups-of-size-k"); + +test("Return the divided groups, each of them has exactyly k characters", () => { + expect(divideString("abcdefghi", 3, "x")).toEqual(["abc","def","ghi"]); +}); + +test("Return the divided groups, every group of them but the last one has exactly k characters", () => { + expect(divideString("abcdefghij", 3, "x")).toEqual(["abc","def","ghi","jxx"]); +}); + +test("Return the divided groups, the last group of them is not filled with the character fill if the character fill is empty", () => { + expect(divideString("abcdefghij", 3, "")).toEqual(["abc","def","ghi","j"]); +});