Search code examples
javascriptenumsiterationgoogle-closuregoogle-closure-library

How do I iterate over enum values in Google Closure?


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?


Solution

  • 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.