index.js 976 Bytes
const DEBUG = process.env['DEBUG'];

const validator = require('./validator');

function reverseString(str) {
    return str.split('').reverse().join('');
}

module.exports = (src, maxLength) => {
    const head = src.slice(0, maxLength);
    const tail = src.slice(maxLength);
    
    if (validator(head, tail)) {
        if (DEBUG) console.log(`TRUNCATE-PARAGRAPH: straight result src='${src}' maxLength=${maxLength}`);
        return [head.trim(), tail.trim()];
    }

    const reverseI = reverseString(head).search(/[\n., ;-]/);
    if (reverseI === -1) {
        // if (DEBUG) console.log(`TRUNCATE-PARAGRAPH: out of boundary src='${src}' maxLength=${maxLength}`);
        return [head.trim(), tail.trim()];
    }

    const i = src.slice(0, maxLength - reverseI).trim().length;
    // if (DEBUG) console.log(`TRUNCATE-PARAGRAPH: calculated src='${src}' maxLength=${maxLength} i=${i}`);
    return [
        src.slice(0, i).trim(),
        src.slice(i).trim(),
    ]
}