Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript list inference


May 09, 2021 CoffeeScript


Table of contents


List inference

Problem

You have an array of objects that you want to map to another array, similar to Python's list inference.

Solution

Use lists to infer, but don't forget that there's also a "mapping-arrays" http://coffeescript-cookbook.github.io/chapters/arrays/mapping-arrays.

electric_mayhem = [ { name: "Doctor Teeth", instrument: "piano" },
                    { name: "Janice", instrument: "lead guitar" },
                    { name: "Sgt. Floyd Pepper", instrument: "bass" },
                    { name: "Zoot", instrument: "sax" },
                    { name: "Lips", instrument: "trumpet" },
                    { name: "Animal", instrument: "drums" } ]

names = (muppet.name for muppet in electric_mayhem)
# => [ 'Doctor Teeth', 'Janice', 'Sgt. Floyd Pepper', 'Zoot', 'Lips', 'Animal' ]

Discuss

Because CoffeeScript directly supports list inference, they work well when you use a Python statement. F or simple mappings, list inferences are more readable. However, for complex transformations or chain mapping, mapping arrays may be more appropriate.