How do I iterate over enum values in Google Closure?

Technetium picture Technetium · Nov 6, 2012 · Viewed 8.7k times · Source

I'm trying to find the best way to iterate over all of the values on an enum defined in Google Closure. Let's say I have the following enum defined:

/**
 * @enum {number}
 */
sample.namespace.Fruit = {
  Orange: 0,
  Apple: 1,
  Banana: 2
};

Right now, the best way I've seen to do this would be something like this:

for (var key in sample.namespace.Fruit) {
    var fruit = /** @type {sample.namespace.Fruit} */ (sample.namespace.Fruit[key]);
    // Make a smoothie or something.
}

I consider that painful to read. I'm listing a namespace three times just to get the compiler to come along for the ride. Is there another iteration technique that I should be using instead? Is this the best way to accomplish this form of iteration?

Answer

Derek Slager picture Derek Slager · Nov 6, 2012

You can use goog.object.forEach to avoid namespace repetition.

goog.object.forEach(sample.namespace.Fruit,
                    function(value, key, allValues) {
                      // Make some delicious fruit jellies or something.
                    });

As a side note, in most cases you want to avoid using string keys for @enums so the compiler can rename those.