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?
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.
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.
Because it's a very comprehensive way to describe a sequence (a set in math and other languages, and a list/sequence in Python).
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With