Brian M. Hunt Brian M. Hunt - 1 month ago 7
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) {
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. :)

Answer

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 = i.next(); !v.done)
  console.log v.value

For a map:

i = m.entries()
while(v = i.next(); !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 = i.next(); !v.done)