Last active
January 30, 2021 15:58
-
-
Save donavon/b91a41978dff3a7293c58584a0d56796 to your computer and use it in GitHub Desktop.
segmentize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const segmentize = (str: string, maxLength: number): string[] => { | |
const regex = new RegExp(`.{1,${maxLength}}`, 'g'); | |
return str.match(regex) ?? []; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const segmentize = ( | |
str: string, | |
maxLength: number, | |
segments: string[] = [] | |
): string[] => { | |
if (str.length > maxLength) { | |
const segment = str.substr(0, maxLength); | |
const rest = str.substr(maxLength); | |
return segmentize(rest, maxLength, [...segments, segment]); | |
} | |
return [...segments, str]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment