Skip to content

Instantly share code, notes, and snippets.

@rossgoodwin
Last active April 10, 2019 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossgoodwin/836df11d9e692eecbeb74566afabd9b9 to your computer and use it in GitHub Desktop.
Save rossgoodwin/836df11d9e692eecbeb74566afabd9b9 to your computer and use it in GitHub Desktop.
line trimmer
const stopRe = /\band\b|\bor\b|\bbut\b|\bnor\b|\bfor\b|\byet\b|\bso\b|\bin\b|\bon\b|\bto\b|\bof\b|\binto\b|\bwith\b|[\.\!\?]+|[,;:]/igm;
export default { }
// function puncStrip(text) {
// return text; // no processing
// // return text.match(puncStripRe)[1]; // kyle's processing
// }
function shortenLine(line, maxLineLength=64) {
// reduce and normalize whitespace
let lineWs = line.replace(/\s+/igm, ' ').trim();
// if last char not punctuation or whitespace
// assume last token is an incomplete word and drop it
let isNotLastCharPunc = !lineWs.match(/\W$/m);
let lineTrim = lineWs;
if (isNotLastCharPunc) lineTrim = lineWs.replace(/\s[^\s]*$/m, '');
// reduce line if greater than maxLineLength
let curLineLength = lineTrim.length;
if (curLineLength <= maxLineLength) return [lineTrim, isNotLastCharPunc];
let match, stopIxs = [];
while ((match = stopRe.exec(lineTrim)) != null) stopIxs.push(match.index);
// console.log(stopIxs);
let stopIxsCeil = stopIxs.filter(n=>n<=maxLineLength);
// console.log(stopIxsCeil);
let stopIx = -1;
if (stopIxsCeil.length > 0) stopIx = Math.max(...stopIxsCeil);
else {
let consolation = lineTrim.slice(0, maxLineLength-3).replace(/\s[^\s]*$/m, '');
return [consolation+'...', false];
}
// console.log(stopIx);
let outLine = lineTrim.slice(0,stopIx).trim();
return [outLine, !outLine.match(/\W$/m)];
}
export function capitalize(text) {
return text.charAt(0).toUpperCase() + text.substr(1)
}
export function cleanPoem(line1, line2) {
let line1tup = shortenLine(line1), line2tup = shortenLine(line2);
let line1short = line1tup[0], line1punc = line1tup[1];
let line2short = line2tup[0], line2punc = line2tup[1];
return [
capitalize(line1short) + (line1punc?',':''),
line2short + (line2punc?'.':'')
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment