javascript-scripts


function calculateNumberOfMessages(message, messageLength) {
    let inputMessage = message;
    let maximumMessageLength = messageLength;
    let numberOfCutMessages = -1;
    let inputMessageSubstring = null;
    let index = 0;
    
    if (inputMessage.length === 1) numberOfCutMessages += 1;
    
    while (index <= inputMessage.length) {
        inputMessageSubstring = inputMessage.substr(index, maximumMessageLength);
        
        let lengthOfInputMessageSubstring = inputMessageSubstring.length;
        
        if (lengthOfInputMessageSubstring < maximumMessageLength && lengthOfInputMessageSubstring > 1) {
            numberOfCutMessages += 1;
        }
        
        if (inputMessageSubstring.indexOf(' ', maximumMessageLength) !== -1) {
            for (i = maximumMessageLength; i > index; i--) {
                if (inputMessageSubstring.indexOf(' ', i) !== -1) {
                    numberOfCutMessages++;
                    index += i;
                    
                    break;
                }
            }
        } else {
            numberOfCutMessages++;
            index += maximumMessageLength;
        }
    }
    
    return numberOfCutMessages;
}