From a8c2304a2b8dcb52e9cc515e7dbfa519b97a9109 Mon Sep 17 00:00:00 2001 From: marihachi <marihachi0620@gmail.com> Date: Sun, 28 Mar 2021 21:14:33 +0900 Subject: [PATCH] add extract API --- src/index.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/index.ts b/src/index.ts index 85289f2..a44cd2c 100644 --- a/src/index.ts +++ b/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, -- GitLab