Standard @iter module unfriendly to collection builders

Jason Orendorff jason.orendorff at gmail.com
Tue Nov 15 14:39:29 PST 2011


To address Allen's original question:

I think the Map and Set classes in Harmony mean that not all
structured data is stored as object properties. I think that's a good
thing.

However it does mean that we must have a separation of concerns between
  - iterating over a collection
  - object property inspection
...because I don't see how 'for (p of obj)' can be both the right
syntax for walking an arbitrary object's properties *and* the right
syntax for walking a Set's elements. Someday the "arbitrary object"
will be a Set. And then what?

So if we take that separation of concerns as our maxim, what do we end
up with? Here's a sketch.

Basics:
  for (v of arr)  // each element of an Array
  for (v of set)  // each value in a Set
  for (k of map)  // each key in a Map, following Python

Host objects / libraries:
  for (elt of document.getElementsByTagName('P'))  // DOM
  for (elt of $("div.main p"))  // hypothetical jQuery support

Other styles of iteration:
  for ([i, v] of arr.items())  // index-value pairs (new Array method)
  for ([k, v] of map.items())  // key-value pairs
  for (v of map.values())  // just values, no keys (uncommon use case)

Enumerating properties:
  import * from '@inspect';
  for (p of keys(obj))
  for (v of values(obj))
  for ([p, v] of items(obj))
Or if you don't want to import anything:
  for (p of Object.keys(obj))
  for (p of Object.getOwnPropertyNames(obj))

This makes Map slightly nicer to iterate over than Object. I think Map
is a better, less error-prone Map than Object anyway, so that's
appropriate.

-j


More information about the es-discuss mailing list