jeudi 5 janvier 2017

Optimizing if/else statements while inside a loop

I am writing a web-based tool that will create subtitles from a provided script. While testing I am just using am HTML textarea as the source. There are a few limitations when creating the subtitles:

  • 35 character maximum per line
  • 2 line maximum per section

  • lines that end in a period, exclamation point, or question mark must terminate prior to reaching the 35 character limit

  • if the first line of a section ends in a period, exclamation point, or question mark there is no second line

I've pasted the parseScript() code here.

var textValue = textarea.value.replace(/\n|\r/gi, " ");
var textArray = textValue.split(" ");

var finalArray = [];
var currentLine = "";
for (var i = 0; i < textArray.length; i++) {
    var word = textArray[i];

    if (currentLine.length + (word.length + 1) <= 35) {
        currentLine += " " + word;
        if (currentLine.match(/\.|\?|\!/g)) {
            finalArray.push(currentLine.trim());
            currentLine = "";
        }
    } else {
        finalArray.push(currentLine.trim());
        currentLine = word;
        if (currentLine.match(/\.|\?|\!/g)) {
            finalArray.push(currentLine.trim());
            currentLine = "";
        }
    }
}

var finalString = "";
var currentString = "";
for (var x = 0; x < finalArray.length; x++) {
    currentString = "<p>" + finalArray[x];
    if (currentString.match(/\.|\?|\!/g)) {
        currentString += "</p>";
    } else {
        currentString += "<br />" + finalArray[x + 1] + "</p>";
        x++;
    }
    finalString += currentString;
    currentString = "";
}
result.innerHTML = finalString;

Everything works great. However the code seems repetitive and can probably be optimized. Specifically, the if/else statement in the first for() loop. Does anyone have any suggestions?

Aucun commentaire:

Enregistrer un commentaire