Skip to content

Commit

Permalink
feat(typescript): str_split
Browse files Browse the repository at this point in the history
  • Loading branch information
nblfikr committed Oct 9, 2022
1 parent f9d48b1 commit 9c3a181
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions typescript/src/string/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./explode";
export * from "./implode";
export * from "./str_repeat";
export * from "./str_split";
25 changes: 25 additions & 0 deletions typescript/src/string/str_split.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { str_split } from "./str_split";

const str = "Hello World!";

describe("string split", () => {
it("should be able to return every letter as element of the array", () => {
expect(str_split(str)).toEqual(
["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d", "!"]
);
});

it("should be able to return 2 or more letter as element of the array depend on number of len", () => {
expect(str_split(str, 2)).toEqual(["He", "ll", "o ", "Wo", "rl", "d!"]);
expect(str_split(str, 3)).toEqual(["Hel", "lo ", "Wor", "ld!"]);
expect(str_split(str, 4)).toEqual(["Hell", "o Wo", "rld!"]);
});

it("should be able to return false", () => {
expect(str_split(str, -1)).toEqual(false);
});

it("should be able to return the entire string as the only element of the array", () => {
expect(str_split(str, 15)).toEqual(["Hello World!"]);
});
});
30 changes: 30 additions & 0 deletions typescript/src/string/str_split.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* str_split — Convert a string to an array
* @param str - The string to be convert.
* @param len - Maximum length of the chunk.
* @returns If the optional length parameter is specified, the returned array will be broken down into chunks with each being length in length, except the final chunk which may be shorter if the string does not divide evenly. The default length is 1, meaning every chunk will be one byte in size.
*/
export const str_split = (str: string, len?: number): string[] | false => {
if (typeof len !== "undefined" && typeof len === "number") {
if (len < 0) return false;

const arr: string[] = [];
let result = "";
let counter = 0;
for (let i=0; i<str.length; i++) {
result = result + str[i];
counter++;

if (counter === len || i === str.length - 1) {
arr.push(result);
result = "";
counter = 0;
}
}

return arr;
}

return str.split("");
};

0 comments on commit 9c3a181

Please sign in to comment.