Skip to content
This repository was archived by the owner on Sep 18, 2023. It is now read-only.

Allow logical expression in if statement #43

Merged
merged 2 commits into from
Mar 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/rules/no-unchecked-define.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ module.exports = {
create(context) {
definedCustomElements = new Map()
return {
[`IfStatement:matches([test.type=UnaryExpression],[test.type=BinaryExpression]) ${s.customElements.get}`](node) {
[`IfStatement:matches([test.type=UnaryExpression],[test.type=BinaryExpression],[test.type=LogicalExpression]) ${s.customElements.get}`](
node
) {
if (node.parent.type === 'UnaryExpression') {
let unaryCounter = 0
let parent = node.parent
Expand All @@ -22,6 +24,10 @@ module.exports = {
if (unaryCounter % 2 !== 0) {
definedCustomElements.set(node.arguments[0].value, node)
}
} else if (node.parent.type === 'LogicalExpression') {
// Don't do anything. If the parent is a logical expression, we are
// checking for truthiness and we only care about if the element is
// _not_ defined.
} else {
definedCustomElements.set(node.arguments[0].value, node)
}
Expand Down
13 changes: 13 additions & 0 deletions test/no-unchecked-define.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ ruleTester.run('no-unchecked-define', rule, {
{
code: 'if (!window.customElements.get("foo-bar")) { window.customElements.define("foo-bar", class extends HTMLElement {}) } '
},
{
code: 'if (window.customElements && !window.customElements.get("foo-bar")) { window.customElements.define("foo-bar", class extends HTMLElement {}) } '
},
{
code: 'if (!customElements.get("foo-bar")) { window.customElements.define("foo-bar", class extends HTMLElement {}) } '
},
Expand Down Expand Up @@ -41,6 +44,16 @@ ruleTester.run('no-unchecked-define', rule, {
}
]
},
{
code: 'if (window.customElements && customElements.get("foo-bar")) { window.customElements.define("foo-bar", class extends HTMLElement {}) } ',
errors: [
{
message:
'Make sure to wrap customElements.define calls in checks to see if the element has already been defined',
type: 'CallExpression'
}
]
},
{
code: 'if (!customElements.get("bar-foo")) { window.customElements.define("foo-bar", class extends HTMLElement {}) } ',
errors: [
Expand Down