Transform more for loops to for-of by auto-generating loop variable name #169

Open
nene opened this Issue Aug 19, 2016 · 0 comments

Projects

None yet

1 participant

@nene
Collaborator
nene commented Aug 19, 2016

Currently for-of transform can handle the case where user has provided a name for the loop variable:

for (let i = 0; i < fruits.length; i++) {
   let fruitItem = fruits[i];
   console.log(fruitItem);
}
// -->
for (let fruitItem of fruits) {
   console.log(fruitItem);
}

At other times we could to make up the name by ourselves. A fairly good case is when the array is named in plural then we can pick a variable name that's the singular form of it:

for (let i = 0; i < fruits.length; i++) {
   console.log(fruits[i]);
}
// -->
for (let fruit of fruits) {
   console.log(fruit);
}

I'm not really sure what to do with other cases where we're looping over a variable like array. Perhaps we can add -Item suffix:

for (let i = 0; i < array.length; i++) {
   console.log(array[i]);
}
// -->
for (let arrayItem of array) {
   console.log(arrayItem);
}

But this way we might also end up with silly stuff like itemItem.

Automatically generating useful variable names is a tricky business...

Also when we introduce a new name we'll also have to watch out for possible existing variables with the same name, like:

let fruit = "banana";
for (let i = 0; i < fruits.length; i++) {
   console.log(fruits[i]);
}
@nene nene added the enhancement label Aug 19, 2016
@aboyton aboyton pushed a commit to aboyton/lebab that referenced this issue Oct 11, 2016
Andrew Boyton Add support for forEach transformation
This adds support for transforming simple for loops into `forEach`
loops.

This builds on the code for transforming for loops into `for-each` loops
and refactors the code to share as much as possible.

This code adds the index and array as required.

To simplifiy the transformation of old code by allowing the author to
name the loop variable at the start of the code and then lebab will do
this rewriting in the rest of the loop.

So, taking the example from #169.

```
for (let i = 0; i < fruits.length; i++) {
   let fruitItem = fruits[i];
   console.log(fruits[i]);
}
// -->
fruits.forEach(fruitItem => {
   console.log(fruitItem);
});
```

or a more complicated example

```
for (let i = 0; i < xs.length; i++) {
  const x = xs[i];
  console.log(xs[i]);
  for (let j = 0; j < xs[i].length; j++) {
    const y = xs[i][j];
    console.log(xs[i][j]);
  }
}
// -->
xs.forEach(x => {
  console.log(x);
  x.forEach(y => {
    console.log(y);
  });
});
```
d76418d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment