Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions 2138.divide-a-string-into-groups-of-size-k.js
Original file line number Diff line number Diff line change
@@ -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;
13 changes: 13 additions & 0 deletions divideString.test.js
Original file line number Diff line number Diff line change
@@ -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"]);
});