Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Converts a string of text into an array of text blocks
/**
* 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
You can’t perform that action at this time.