Skip to content

Instantly share code, notes, and snippets.

@reeddunkle
Last active June 4, 2020 15:56
Show Gist options
  • Select an option

  • Save reeddunkle/8be21178fadba049165852f5bc4c4913 to your computer and use it in GitHub Desktop.

Select an option

Save reeddunkle/8be21178fadba049165852f5bc4c4913 to your computer and use it in GitHub Desktop.
Partial solution to trucate rich text AST
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