Last active
October 11, 2019 22:54
-
-
Save ArtemKorchunov/92974b507bb7e935cd246a5c45c756c6 to your computer and use it in GitHub Desktop.
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
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