How can one iterate over an ES6 Map or Set in Coffeescript?
In Javascript one would use e.g.
s = new Set()
s.add({a: 1})
for (x of s) {
console.log(x);
}
However Coffeescript has its own of
operator that gets converted to in
, i.e.:
console.log(x) for x of s
becomes ... for (x in s) { ... }
.
How can one access Javascript's of
operator in Coffeescript?
One could write their own custom iterator by cycling over s.values().next()
, but that'd be an abomination. :)
Coffeescript 2.0 —
for …from
Coffeescript 1.0 — Backticks
One option is to use the backtick to embed raw Javascript i.e. http://coffeescript.org/#embedded.
You want to do something like this:
(where
eat
is a function)In your case, you would do:
Ref: http://coffeescript.org/#loops
It's helpful to use the coffeescript REPL. You can open it by typing
coffee
in your console. Try the following code:Edit:
Unfortunately, the Set functionality from ES6 doesn't seem to have made it into Coffeescript yet. Consider using underscore the lodash methods
_.unique()
or_.union()
to mimic the functionality you're looking for.For the example above:
There's currently no way to use the new Javascript ES6
of
operator from coffeescript (as of 1.9.2). The best option for now is to uses.forEach (x) -> ...
orm.forEach (value, key) ->
as mentioned above.For a set:
For a map:
If you want to avoid creating new functions for whatever reason, you can use iterators directly from coffeescript. But its a little bit nasty. For sets:
For a map:
The parentheses on the while loop are necessary to make the while loop dependant on v.done.
They can be done on one line too - but it looks pretty bad: