Skip to content

Commit 8568a35

Browse files
committed
feat: added a util for counting element occurences
1 parent 23822b6 commit 8568a35

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import type { AST } from 'svelte-eslint-parser';
2+
3+
export enum ElementOccurenceCount {
4+
ZeroOrOne,
5+
One,
6+
ZeroToInf
7+
}
8+
9+
function multiplyCounts(
10+
left: ElementOccurenceCount,
11+
right: ElementOccurenceCount
12+
): ElementOccurenceCount {
13+
if (left === ElementOccurenceCount.One) {
14+
return right;
15+
}
16+
if (right === ElementOccurenceCount.One) {
17+
return left;
18+
}
19+
if (left === right) {
20+
return left;
21+
}
22+
return ElementOccurenceCount.ZeroToInf;
23+
}
24+
25+
function childElementOccurenceCount(parent: AST.SvelteHTMLNode | null): ElementOccurenceCount {
26+
if (parent === null) {
27+
return ElementOccurenceCount.One;
28+
}
29+
if (
30+
[
31+
'SvelteIfBlock',
32+
'SvelteElseBlock',
33+
'SvelteAwaitBlock',
34+
'SvelteAwaitPendingBlock',
35+
'SvelteAwaitThenBlock',
36+
'SvelteAwaitCatchBlock'
37+
].includes(parent.type)
38+
) {
39+
return ElementOccurenceCount.ZeroOrOne;
40+
}
41+
if (
42+
['SvelteEachBlock', 'SvelteSnippetBlock'].includes(parent.type) ||
43+
(parent.type === 'SvelteElement' && parent.kind === 'component')
44+
) {
45+
return ElementOccurenceCount.ZeroToInf;
46+
}
47+
return ElementOccurenceCount.One;
48+
}
49+
50+
export function elementOccurrenceCount(element: AST.SvelteHTMLNode): ElementOccurenceCount {
51+
const parentCount =
52+
element.parent !== null ? elementOccurrenceCount(element.parent) : ElementOccurenceCount.One;
53+
const parentChildCount = childElementOccurenceCount(element.parent);
54+
return multiplyCounts(parentCount, parentChildCount);
55+
}

0 commit comments

Comments
 (0)