Skip to content

Commit 5047a5a

Browse files
Merge pull request #41 from oxidecomputer/dedupe-footnotes
Return of the cache (getContent)
2 parents cf7a887 + d862514 commit 5047a5a

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/asciidoc/utils/prepareDocument.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,35 @@ export const hasAttribute = (attrs: Record<string, string | number>, name: strin
241241
return attrs[name] !== undefined
242242
}
243243

244+
const contentCache: { [key: string]: string } = {}
245+
type Node = AdocTypes.Block | AdocTypes.AbstractBlock | AdocTypes.Table.Cell
246+
247+
const getContent = (node: Node) => {
248+
const cacheKey = (node as Node & { $$id: string }).$$id
249+
250+
if (contentCache[cacheKey]) {
251+
return contentCache[cacheKey]
252+
}
253+
254+
const newContent = (node.getContent && node.getContent()) || ''
255+
contentCache[cacheKey] = newContent
256+
return newContent
257+
}
258+
259+
const getText = (
260+
node: AdocTypes.ListItem | AdocTypes.Document.Footnote | AdocTypes.Table.Cell,
261+
) => {
262+
const cacheKey = (node as Node & { $$id: string }).$$id
263+
264+
if (contentCache[cacheKey]) {
265+
return contentCache[cacheKey]
266+
}
267+
268+
const newContent = (node.getText && node.getText()) || ''
269+
contentCache[cacheKey] = newContent
270+
return newContent
271+
}
272+
244273
export const prepareDocument = (document: AdocTypes.Document) => {
245274
let preparedDocument: DocumentBlock
246275

@@ -256,7 +285,7 @@ export const prepareDocument = (document: AdocTypes.Document) => {
256285
id: block.getId && block.getId(),
257286
type,
258287
blocks,
259-
content: blocks.length > 0 ? undefined : block.getContent && block.getContent(),
288+
content: blocks.length > 0 ? undefined : getContent(block),
260289
attributes: block.getAttributes && block.getAttributes(),
261290
contentModel,
262291
lineNumber: block.getLineNumber && block.getLineNumber(),
@@ -348,7 +377,7 @@ export const prepareDocument = (document: AdocTypes.Document) => {
348377
if (type === 'list_item') {
349378
let listItemBlock = processedBlock as ListItemBlock
350379
const adocListItem = block as unknown as AdocTypes.ListItem
351-
listItemBlock.text = adocListItem.hasText() ? adocListItem.getText() : undefined
380+
listItemBlock.text = adocListItem.hasText() ? getText(adocListItem) : undefined
352381
}
353382

354383
if (type === 'table') {
@@ -401,7 +430,7 @@ export const prepareDocument = (document: AdocTypes.Document) => {
401430
let tableCellBlock: Cell = {
402431
...processedBlock,
403432
type: 'table_cell',
404-
text: adocListItem.getText(),
433+
text: getText(adocListItem),
405434
columnSpan: adocListItem.getColumnSpan(),
406435
rowSpan: adocListItem.getRowSpan(),
407436
source: adocListItem.getSource(),

0 commit comments

Comments
 (0)