Skip to content

Commit c792aec

Browse files
committed
feat: added a util for counting element occurences
1 parent 3b06fd9 commit c792aec

File tree

1 file changed

+52
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)