Brian M. Hunt Brian M. Hunt - 10 months ago 77
CoffeeScript Question

Iterate over ES6 Set/Map in Coffeescript (with `of` operator)

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) {

However Coffeescript has its own
operator that gets converted to
, i.e.:

console.log(x) for x of s

... for (x in s) { ... }

How can one access Javascript's
operator in Coffeescript?

One could write their own custom iterator by cycling over
, but that'd be an abomination. :)

Answer Source

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 use s.forEach (x) -> ... or m.forEach (value, key) -> as mentioned above.

For a set:

s = new Set
s.add {a: 1}

s.forEach (v) =>
  console.log v

For a map:

m = new Map
m.set {a: 1}, {b: 2}

m.forEach (v, k) =>
  console.log k, v

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:

i = s.values()
while(v =; !v.done)
  console.log v.value

For a map:

i = m.entries()
while(v =; !v.done)
  [key, value] = v.value
  console.log key, value

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:

i = s.values(); console.log v.value while(v =; !v.done)