Last active
February 13, 2019 18:23
-
-
Save wasinsandiego/968a6116344b5204fed304ad27796528 to your computer and use it in GitHub Desktop.
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
const warning = (maxLength, startLimit, endLimit, delimiter) => ( | |
console.warn(`middleEllipsis :: The start (${startLimit}) and end \ | |
(${endLimit}) plus the delimiter (${delimiter}) add up to more than \ | |
the limit (${startLimit + endLimit + delimiter.length} > ${maxLength}). \ | |
This will produce a truncated string larger than your maxLength.`) | |
) | |
const middleEllipsis = ({ text = '', maxLength = 47, start, end, delimiter = '...' }) => { | |
if (text.length < maxLength) { return text } | |
const startLimit = start || Math.floor((maxLength - delimiter.length) / 1.6) | |
const endLimit = end || Math.floor(maxLength - delimiter.length - startLimit) | |
if (start && end && startLimit + endLimit + delimiter.length > maxLength) { | |
warning(maxLength, startLimit, endLimit, delimiter) | |
} | |
return `${text.substring(0, startLimit)}${delimiter}${text.substring(text.length - endLimit, text.length)}` | |
} | |
const middleEllipsisTagFactory = ({ maxLength, start, end, delimiter }) => ( | |
(texts, ...rest) => middleEllipsis({ | |
text: texts.reduce((str, text, index) => `${str}${text}${rest[index] ? rest[index] : ''}`, ''), | |
maxLength, start, end, delimiter | |
}) | |
) | |
const truncateMiddleMax10 = middleEllipsisTagFactory({ maxLength: 10 }) | |
truncateMiddleMax10`This is some long text that must be truncated!` | |
// output --> 'This...ed!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment