import { Parent , Node } from "unist" ; import visit from "unist-util-visit-parents" ; import remove from "unist-util-remove" ; function addValue ( data , path , value ) { const existingValue = data ! [ path ] ; if ( ! existingValue ) { data ! [ path ] = value ; } else { data ! [ "+" + path ] = ( ( data ! [ "+" + path ] as any [ ] ) || [ ] ) . concat ( value ) ; } } param root param removeNodes returns export function compact ( root , removeNodes = [ "TRLR" , "SUBM" , "SUBN" , "HEAD" , "NOTE" , "SOUR" ] ) { remove ( root , removeNodes ) ; for ( let child of root . children ) { if ( ! child . data ) child . data = { } ; visit ( child , ( node , ancestors ) => { const path = ancestors . slice ( 1 ) . concat ( node ) . map ( ( a ) => a . data ?. formal_name || a . type ) . join ( "/" ) ; if ( node . value ) { addValue ( child . data ! , path , node . value ) ; } else if ( node . data ?. pointer ) { addValue ( child . data ! , `@${ path }` , node . data . pointer ) ; } } ) ; child . children = [ ] ; } return root ; }