Skip to content

Commit

Permalink
Add more methods
Browse files Browse the repository at this point in the history
  • Loading branch information
lxsmnsyc committed Oct 25, 2024
1 parent 0e49282 commit 79f1b13
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions packages/core/babel/core/unwrap-node.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { NodePath } from '@babel/traverse';
import type * as t from '@babel/types';

type TypeFilter<K extends t.Node> = (node: t.Node) => node is K;
Expand Down Expand Up @@ -28,6 +29,13 @@ function isNestedExpression(node: t.Node): node is NestedExpression {
}
}

export function isPathValid<V extends t.Node>(
path: unknown,
key: TypeFilter<V>,
): path is NodePath<V> {
return key((path as NodePath).node);
}

export default function unwrapNode<K extends (node: t.Node) => boolean>(
node: t.Node,
key: K,
Expand All @@ -40,3 +48,22 @@ export default function unwrapNode<K extends (node: t.Node) => boolean>(
}
return undefined;
}

export function getProperParentPath<K extends (node: t.Node) => boolean>(
path: NodePath,
key: K,
): NodePath<TypeCheck<K>> | undefined {
let parent = path.parentPath;

while (parent) {
if (isNestedExpression(parent.node)) {
parent = parent.parentPath;
} else if (key(parent.node)) {
return parent as NodePath<TypeCheck<K>>;
} else {
return undefined;
}
}

return undefined;
}

0 comments on commit 79f1b13

Please sign in to comment.