Blame view
lib/truncate-paragraph/index.js
976 Bytes
76a4bcfcc
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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(/[ ., ;-]/); 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(), ] } |