|
|
|
|
|
by dkopi
3710 days ago
|
|
List comprehensions are incredible.
But they're just syntactic sugar for map() and filter() and lambdas. Python's prev = [1,2,3,4]
next = [x * 2 for x in old]
Is the same as javascript's prev = [1,2,3,4];
next = prev.map(x => x * 2);
Python's next = [x for x in prev if x % 2 == 0]
is the same as javascript's next = prev.filter(x => x % 2 === 0);
And finally, python's next = [x * 2 for x in prev if x % 2 == 0]
is the same as next = prev.filter(x => x % 2 == 0).map(x => x * 2);
It could be nice to have a "mapIf" function that accepts a mapping and a predicate, but I think the extra verbosity makes the above code easier to understand. next = prev.mapIf(x => x * 2, x => x % 2 == 0);
|
|
At this point it feels to me, and probably to many other devs and also JS engine implementors, that list comprehensions are such a small improvement over map() and filter() that for now it may simply not be worth introducing another feature into the language when there's already so much being worked on, especially things that will yield much more pronounced improvements to JS language ergonomics with not that much more effort required than for example list comprehensions would take.
(Maybe if we tackle the addition of list comprehensions at a later point, we'll be able to get that neat-o postfix if statement in as well, for a low cost. But I'm just daydreaming (mostly) and speculating (a bit) here!)
(Edit: formatting)