Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of a list comprehension like this one in ES2016 or greater?

Python 3.6:

[f"Cat #{n}" for n in range(5)]

gives

['Cat #0', 'Cat #1', 'Cat #2', 'Cat #3', 'Cat #4']

New to JavaScript, What's the equivalent in new EcmaScript?

like image 877
Aymon Fournier Avatar asked Jul 25 '17 18:07

Aymon Fournier


People also ask

What is comprehension equivalent in Python?

We can create new sequences using a given python sequence. This is called comprehension. It basically a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using another sequence.

Does TypeScript have list comprehension?

List Comprehension for TypeScript. This library implements comprehension for arrays, sets and maps for TypeScript. It also offer a powerful library to construct populated arrays that can be used with the comprehension functions.

Why is it called list comprehension?

Because it's a very comprehensive way to describe a sequence (a set in math and other languages, and a list/sequence in Python).

What is the difference between list comprehension and for loop?

The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code. List comprehension requires less computation power than a for loop because it takes up less space and code.


1 Answers

Use the combination of Generator and Spread Operator.

ES2015:

[...(function*(){for(let n=0;n<5;)yield'Cat #'+n++})()]

gives

["Cat #0", "Cat #1", "Cat #2", "Cat #3", "Cat #4"]
like image 115
shinji709 Avatar answered Oct 21 '22 02:10

shinji709