Created
May 24, 2019 20:42
-
-
Save matpratta/a929e11ed054cdc491fa67c01e9f0bfd to your computer and use it in GitHub Desktop.
Converts a string of text into an array of text blocks
This file contains hidden or 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
| /** | |
| * Converts a string of text into an array of text blocks with a maximum size of blockSize. | |
| * @author Matheus Pratta <eu@matheus.io> | |
| * @param {string} text | |
| * @param {int} blockSize | |
| * @returns {array} | |
| */ | |
| function textToCharBlocks (text, blockSize) { | |
| let textBlocks = []; // Array containing our text blocks | |
| let currentBlock = ''; // accumulator | |
| for (let iChar = 0, char; char = text[iChar++];) { | |
| // Adds current char to accumulator | |
| currentBlock += char; | |
| // When block size is reached, push into array and reset accumulator | |
| if (currentBlock.length == blockSize) { | |
| textBlocks.push(currentBlock); | |
| currentBlock = ''; | |
| } | |
| } | |
| // Checks if anything remains in accumulator, if so, push at end of array | |
| if (currentBlock.length > 0) textBlocks.push(currentBlock); | |
| // Returns our array | |
| return textBlocks; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment