Skip to content

Instantly share code, notes, and snippets.

@rossgoodwin
Created April 10, 2019 02:24
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/197657afe265704e6a649da013fa1c38 to your computer and use it in GitHub Desktop.
Save rossgoodwin/197657afe265704e6a649da013fa1c38 to your computer and use it in GitHub Desktop.
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|[\.\!\?\n]+|[,;:]/igm;
export default { }
// function puncStrip(text) {
// return text; // no processing
// // return text.match(puncStripRe)[1]; // kyle's processing
// }
function shortenLine(line, maxLineLength=88) {
// if last char not punctuation or whitespace
// assume last token is an incomplete word and drop it
let isNotLastCharPunc = !line.trim().match(/[;,:\.\?\!]$/igm);
let lineTrim = line;
if (isNotLastCharPunc) lineTrim = line.replace(/\s[^\s]*$/m, '');
// reduce line if greater than maxLineLength
let curLineLength = lineTrim.length;
if (curLineLength <= maxLineLength) return [lineTrim.replace(/\s+/igm, ' ').trim(), 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.replace(/\s+/igm, ' ').trim()+'...', false];
}
// console.log(stopIx);
let outLine = lineTrim.slice(0,stopIx).trim();
return [outLine.replace(/\s+/igm, ' ').trim(), !outLine.trim().match(/[;,:\.\?\!]$/igm)];
}
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