mirror of
https://activitypub.software/TransFem-org/sfm-js
synced 2024-11-28 17:03:03 +00:00
add extract API
This commit is contained in:
parent
909d16c85d
commit
a8c2304a2b
1 changed files with 23 additions and 0 deletions
23
src/index.ts
23
src/index.ts
|
@ -33,6 +33,29 @@ export function inspect(tree: MfmNode[], action: (node: MfmNode) => void): void
|
|||
}
|
||||
}
|
||||
|
||||
export function extract(nodes: MfmNode[], type: (MfmNode['type'] | MfmNode['type'][])): MfmNode[] {
|
||||
function predicate(node: MfmNode, type: (MfmNode['type'] | MfmNode['type'][])): boolean {
|
||||
if (Array.isArray(type)) {
|
||||
return (type.some(i => i == node.type));
|
||||
}
|
||||
else {
|
||||
return (type == node.type);
|
||||
}
|
||||
}
|
||||
|
||||
const dest = [] as MfmNode[];
|
||||
for (const node of nodes) {
|
||||
if (predicate(node, type)) {
|
||||
dest.push(node);
|
||||
}
|
||||
if (node.children != null) {
|
||||
dest.push(...extract(node.children, type));
|
||||
}
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
export {
|
||||
MfmNode,
|
||||
MfmBlock,
|
||||
|
|
Loading…
Reference in a new issue