/
helpers.ts
79 lines (71 loc) · 2.47 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { AST_NODE_TYPES, AST_TOKEN_TYPES, TSESTree } from '../ts-estree';
type ObjectEntry<BaseType> = [keyof BaseType, BaseType[keyof BaseType]];
type ObjectEntries<BaseType> = Array<ObjectEntry<BaseType>>;
export const isNodeOfType =
<NodeType extends AST_NODE_TYPES>(nodeType: NodeType) =>
(
node: TSESTree.Node | null | undefined,
): node is TSESTree.Node & { type: NodeType } =>
node?.type === nodeType;
export const isNodeOfTypes =
<NodeTypes extends readonly AST_NODE_TYPES[]>(nodeTypes: NodeTypes) =>
(
node: TSESTree.Node | null | undefined,
): node is TSESTree.Node & { type: NodeTypes[number] } =>
!!node && nodeTypes.includes(node.type);
export const isNodeOfTypeWithConditions = <
NodeType extends AST_NODE_TYPES,
Conditions extends Partial<TSESTree.Node & { type: NodeType }>,
>(
nodeType: NodeType,
conditions: Conditions,
): ((
node: TSESTree.Node | null | undefined,
) => node is TSESTree.Node & { type: NodeType } & Conditions) => {
const entries = Object.entries(conditions) as ObjectEntries<
TSESTree.Node & { type: NodeType }
>;
return (
node: TSESTree.Node | null | undefined,
): node is TSESTree.Node & { type: NodeType } & Conditions =>
node?.type === nodeType &&
entries.every(([key, value]) => node[key] === value);
};
export const isTokenOfTypeWithConditions = <
TokenType extends AST_TOKEN_TYPES,
Conditions extends Partial<TSESTree.Token & { type: TokenType }>,
>(
tokenType: TokenType,
conditions: Conditions,
): ((
token: TSESTree.Token | null | undefined,
) => token is TSESTree.Token & { type: TokenType } & Conditions) => {
const entries = Object.entries(conditions) as ObjectEntries<
TSESTree.Token & { type: TokenType }
>;
return (
token: TSESTree.Token | null | undefined,
): token is TSESTree.Token & { type: TokenType } & Conditions =>
token?.type === tokenType &&
entries.every(([key, value]) => token[key] === value);
};
export const isNotTokenOfTypeWithConditions =
<
TokenType extends AST_TOKEN_TYPES,
Conditions extends Partial<TSESTree.Token & { type: TokenType }>,
>(
tokenType: TokenType,
conditions: Conditions,
): ((
token: TSESTree.Token | null | undefined,
) => token is Exclude<
TSESTree.Token,
TSESTree.Token & { type: TokenType } & Conditions
>) =>
(
token,
): token is Exclude<
TSESTree.Token,
TSESTree.Token & { type: TokenType } & Conditions
> =>
!isTokenOfTypeWithConditions(tokenType, conditions)(token);