Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule proposal: avoid loops to create URLSearchParams #2269

Open
fregante opened this issue Feb 5, 2024 · 6 comments
Open

Rule proposal: avoid loops to create URLSearchParams #2269

fregante opened this issue Feb 5, 2024 · 6 comments

Comments

@fregante
Copy link
Collaborator

fregante commented Feb 5, 2024

Description

It might be a bit niche, but not everyone knows that you can convert an object to a URLSearchParams without a for loop.

Fail

const tokenParams = new URLSearchParams();
for (const [param, value] of Object.entries(tokenBody)) {
  tokenParams.set(param, value);
}
new URLSearchParams(Object.entries(tokenBody))

Pass

new URLSearchParams(tokenBody)
// This piece of code is adding entries to an existing `URLSearchParam`
for (const [param, value] of Object.entries(tokenBody)) {
  tokenParams.set(param, value);
}

Additional Info

No response

@fregante fregante changed the title Rule proposal: prefer obj.entries() to create URLSearchParams Rule proposal: prefer Object.entries() to create URLSearchParams Feb 10, 2024
@silverwind
Copy link
Contributor

silverwind commented Feb 18, 2024

Do you even need the Object.entries? You haven't told what tokenBody is.

> new URLSearchParams(Object.entries({a: 1}))
URLSearchParams { 'a' => '1' }
> new URLSearchParams({a: 1})
URLSearchParams { 'a' => '1' }

@fregante
Copy link
Collaborator Author

Judging by MDN, that's seems to be accepted. I think the problem used to be typescript, but that works now too

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

@fregante fregante changed the title Rule proposal: prefer Object.entries() to create URLSearchParams Rule proposal: avoid loops to create URLSearchParams Feb 18, 2024
@silverwind
Copy link
Contributor

silverwind commented Feb 19, 2024

I guess this rule could apply to more than just URLSearchParams, basically anything that accepts a iterable in its constructor. Set is such an example, FormData is not. I'd call it prefer-iterable-in-constructor.

@fregante
Copy link
Collaborator Author

Objects are not iterable

@silverwind
Copy link
Contributor

silverwind commented Feb 19, 2024

Right, so URLSearchParams is special in that it accepts objects, but the basic idea is the same in all cases, avoid a loop when a constructor can do the looping itself.

@sindresorhus
Copy link
Owner

Accepted. prefer-iterable-in-constructor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants