Last active
June 4, 2020 15:56
-
-
Save reeddunkle/8be21178fadba049165852f5bc4c4913 to your computer and use it in GitHub Desktop.
Partial solution to trucate rich text AST
This file contains hidden or 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 truncateRichText = (richText, options) => { | |
| let characterCount = 0; | |
| const _truncateRich = (rich) => { | |
| const { children } = rich; | |
| const truncatedChildren = children.reduce((accumulator, node, index) => { | |
| if (characterCount < options.length) { | |
| if (isString(node)) { | |
| const nextCount = characterCount + node.length; | |
| const areAdditionalNodes = index !== children.length - 1; | |
| let textToTruncate; | |
| if (areAdditionalNodes) { | |
| textToTruncate = nextCount < options.length ? node : `${node}1`; | |
| } else { | |
| textToTruncate = node; | |
| } | |
| const truncatedText = truncate(textToTruncate, { | |
| ...options, | |
| length: options.length - characterCount, | |
| }); | |
| characterCount = nextCount; | |
| accumulator.push(truncatedText); | |
| } else { | |
| accumulator.push(_truncateRich(node)); | |
| } | |
| } | |
| return accumulator; | |
| }, []); | |
| return { | |
| ...rich, | |
| children: truncatedChildren, | |
| }; | |
| }; | |
| return isString(richText) | |
| ? truncate(richText, options) | |
| : _truncateRich(richText); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment