Transform forEach loops with if to forEach with a filter #190

Open
aboyton opened this Issue Oct 11, 2016 · 2 comments

Projects

None yet

2 participants

@aboyton
aboyton commented Oct 11, 2016

It's a somewhat common pattern to have an if statement being the only thing in a forEach loop.

numbers.forEach(number => {
    if(number % 2 === 0) {
        console.log(number);
    }
}

This could be transformed to something more functional with a filter.

numbers.filter(number => {
    return (number % 2 !== 0);
}).forEach(number => {
    console.log(number);
});

While this isn't a style everyone might like, I do think it's in the direction much ES6 code is heading and thus I think a useful transformation.

@nene nene added the enhancement label Oct 11, 2016
@nene
Collaborator
nene commented Oct 11, 2016 edited

Yep, this looks like a great idea.

Though in your code example, you have reversed the condition inside filter. A simple mistake I guess.

Would be nice to also have a transform from for-loop to Array.map(), but it seems much trickier. With for-loop one often transforms the array in-place, relying on side-effects, while with .map() you'd be creating a new array... which can be difficult to map to equivalent code. There are some patterns though:

const result = [];
array.forEach(item => {
    result.push(item * 2);
});
// --->
const result = array.map(item => item * 2);
@aboyton
aboyton commented Oct 11, 2016

Argh, even in such a simple example I still make a typo. Guess this is why I like lebab so much ;)

Definitely agree that we could do a lot more transformations like this. map would be a great one, as would reduce. I figured that I'd start by suggesting a simple example that I thought I'd know how to implement to test the waters with seeing what sorts of transformations that you are interested in doing with lebab.

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