Skip to main content

Ivan Teoh

Something personal yet public

170-exercise63.js

(Source)

function splitParagraph(paragraph) {
    var paragraphs = [];

    function spliting(first, last, typeString) {
        while (true)  {
            start = paragraph.indexOf(first, 0);
            if (start == -1) {
                break;
            }
            end = paragraph.indexOf(last, start + 1);
            if (end == -1) {
                break;
            }
            // content does not have "*"
            content = paragraph.slice(start, end + 1).slice(1, -1);
            paragraph = paragraph.slice(0,
                            paragraph.charAt(start) == " "? start - 1 :start)
                            .concat(paragraph.slice(end + 1));
            paragraphs.push({'content': content, 'type': typeString});
        }
    }

    // emphasised part
    spliting("*", "*", "emphasised");

    // footnote
    spliting("{", "}", "footnote");

    // normal text
    paragraphs.push({'content': paragraph, 'type': 'normal'});
    return paragraphs;
}

// [{'content': 'million', 'type': 'emphasised'},
//  {'content': 'mine is almost a lines', 'type': 'normal'}]
console.log(splitParagraph("mine is almost a *million* lines"));
// [{'content': 'Type something!', 'type': 'emphasised'},
//  {'content': "and shouted '' The student", 'type': 'normal'}]
console.log(splitParagraph("and shouted '*Type something!*' The student"));
// [{'content': 'square', 'type': 'emphasised'},
//  {'content': 'result', 'type': 'emphasised'},
//  {'content': 'two and then it again, the is already inaccurate!',
//   'type': 'normal'}]
console.log(splitParagraph("two and then *square* it again, the *result* is " +
"already inaccurate!"));
// [{'content': 'million', 'type': 'footnote'},
//  {'content': 'mine is almost a lines', 'type': 'normal'}]
console.log(splitParagraph("mine is almost a {million} lines"));
// [{'content': 'square', 'type': 'emphasised'},
//  {'content': 'result', 'type': 'footnote'},
//  {'content': 'two and then it again, the is already inaccurate!',
//   'type': 'normal'}]
console.log(splitParagraph("two and then *square* it again, the {result} is " +
"already inaccurate!"));