Skip to content

Instantly share code, notes, and snippets.

@mo7amd
Last active January 21, 2021 13:56
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 mo7amd/7aae6cf7085fc61172504a37bd4ee5a7 to your computer and use it in GitHub Desktop.
Save mo7amd/7aae6cf7085fc61172504a37bd4ee5a7 to your computer and use it in GitHub Desktop.
Truncate method
export const formateToEllipses = (string = '', maxCharAtOneLine, maxLines) => {
const ellipses = '...';
const separator = ' ';
const words = string.split(separator);
let lineNum = 1;
const lines = [];
let line = '';
const addEllipses = str => str.substring(0, maxCharAtOneLine - 3) + ellipses;
const isLargerThanLine = word => word.length > maxCharAtOneLine;
const gotoNewLine = (isEllipses = false, initial = '') => {
line = isEllipses ? addEllipses(line) : line;
lineNum += 1;
lines.push(line);
line = initial;
};
const generateStrWithEllipses = (word, index) => {
const isLongerThanLineWord = isLargerThanLine(word);
const isStillWithinLines = (lineNum < maxLines);
const isLastWord = index === (words.length - 1);
const isFirstWord = index === 0;
const isOneWord = words.length === 1;
const isLastLine = lineNum === maxLines;
const temp = line === '' ? word : `${line} ${word}`;
if (isFirstWord && isLongerThanLineWord) {
line = word;
gotoNewLine(true);
return false;
}
if (isOneWord && !isLongerThanLineWord) {
line = word;
gotoNewLine();
return false;
}
if (isLastLine) {
if (isLargerThanLine(temp) || !isLastWord) {
line = temp;
gotoNewLine(true);
return false;
}
line = temp;
gotoNewLine();
return false;
}
if (isStillWithinLines && isLastWord) {
if (isLargerThanLine(temp)) {
gotoNewLine(false, word);
if (isLargerThanLine(word)) {
gotoNewLine(true);
} else {
gotoNewLine();
}
return false;
}
line = temp;
gotoNewLine();
return false;
}
if (isStillWithinLines && !isLargerThanLine(temp)) {
line = temp;
return;
}
if (isStillWithinLines && isLargerThanLine(temp)) {
gotoNewLine(false, word);
}
};
words.forEach(generateStrWithEllipses);
return lines.join(separator);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment