I am looking to optimise my solution of the 'SMS problem', i.e splitting a String into chunks of the same size without splitting words.
I did a recursion and am looking for ways to optimise that code, or a more efficient algorithm. In my solution spaces are left at the beginning of each chunk, this is voluntary.
Here is the code:
var exampleTxt = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`;
function getIndexOfLastSpace(msg, nthChar) {
var curMsg = msg.substring(0, nthChar);
console.log(curMsg.lastIndexOf(" "));
return curMsg.lastIndexOf(" ");
}
function getMessagesNumber (msg) {
if (msg.length < 1) {
return 0;
} else if (msg.length > 1 & msg.length < 153) {
return 1;
} else {
var messages = [];
while (msg.length > 0) {
var chunk;
// Last message
if (msg.length <= 153) {
chunk = msg;
} else {
var lastSpaceIndex = getIndexOfLastSpace(msg, 153);
chunk = msg.substring(0, lastSpaceIndex);
}
messages.push(chunk);
msg = msg.replace(chunk, '');
}
return messages.length;
}
}
console.log(getMessagesNumber(exampleTxt));
Also am I write in thinking that the complexity of this algorithm is O(n) ?