Skip to content

Instantly share code, notes, and snippets.

@ArtemKorchunov
Last active October 11, 2019 22:54
Show Gist options
  • Save ArtemKorchunov/92974b507bb7e935cd246a5c45c756c6 to your computer and use it in GitHub Desktop.
Save ArtemKorchunov/92974b507bb7e935cd246a5c45c756c6 to your computer and use it in GitHub Desktop.
function solution(fullMesssage, maxLength) {
const space = ' ';
const wordsArr = fullMesssage.split(space);
const isSomeWordOutOfBoundary = Boolean(
wordsArr.some(word => word.length > maxLength)
);
if (isSomeWordOutOfBoundary) {
return -1;
}
const resultedMessagesArr = [];
let currentMessage = '';
wordsArr.forEach((word, index) => {
const resultedMessage = (currentMessage + space + word).trim();
const resultedMessageLength = resultedMessage.length;
if (resultedMessageLength < maxLength) {
currentMessage = resultedMessage
} else if (resultedMessageLength > maxLength) {
resultedMessagesArr.push(currentMessage);
currentMessage = word;
} else {
resultedMessagesArr.push(resultedMessage);
currentMessage = '';
}
})
if (currentMessage.length) {
resultedMessagesArr.push(currentMessage);
}
return resultedMessagesArr.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment