Last active
January 21, 2021 13:56
-
-
Save mo7amd/7aae6cf7085fc61172504a37bd4ee5a7 to your computer and use it in GitHub Desktop.
Truncate method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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