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

Transform [].forEach => for-in #124

Open
kristoferbaxter opened this issue Dec 11, 2018 · 1 comment
Open

Transform [].forEach => for-in #124

kristoferbaxter opened this issue Dec 11, 2018 · 1 comment
Assignees

Comments

@kristoferbaxter
Copy link
Contributor

kristoferbaxter commented Dec 11, 2018

Is your feature request related to a problem? Please describe.

Many [].forEach calls can be converted to a for...in safely.

const LANGUAGES = { javascript, json, xml };
Object.keys(LANGUAGES).forEach( key => hljs.registerLanguage(key, LANGUAGES[key]) );

Can be converted to...

const LANGUAGES = { javascript, json, xml };
for (key in LANGUAGES) { hljs.registerLanguage(key, LANGUAGES[key]) }

Describe the solution you'd like

This transform can be done safely so long as the inner function doesn't rely on this being auto bound.

It's worth investigating if there are cases where a function call can be generated that passes the scope as an argument and leverages it correctly as well.

Describe alternatives you've considered

Ignore this transform entirely.

Edit: If order is important, for...of is a better choice.

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

@kristoferbaxter kristoferbaxter self-assigned this Dec 11, 2018
@kristoferbaxter
Copy link
Contributor Author

kristoferbaxter commented Jan 14, 2020

Note: Can create a unique key for all for ... of and leverage it in each instance.

x.forEach(v=>add(v)); => for(z of x){add(z)}

Pros: Shorter consistent syntax.
Cons: Global variable lookup, hoisted module locals are cheapest to assign/read.

Alternative: Create a local per module for this and let variable folding keep it terse.

let z;
for(z of x){add(z)}

Caveat: Nested loops!

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

No branches or pull requests

1 participant