Recopilación e iteración con ES6

Aunque la especificación de ECMAScript 6 aún está en formato borrador, promete muchas herramientas nuevas y emocionantes para agregar al cinturón de los programadores de JavaScript. Las clases nuevas, como Set y Map, ofrecen soluciones nativas para trabajar con tipos específicos de colecciones, y la sentencia for...of proporciona una alternativa elegante a las formas tradicionales de iterar sobre datos.

Los elementos Set ofrecen una forma de hacer un seguimiento de una colección de elementos en los que cada elemento puede aparecer como máximo una vez. Los elementos Map ofrecen más funcionalidades de lo que era posible antes, ya que usan Object para asociar claves con valores. Con un Map, no es necesario que tus claves sean cadenas y no tienes que preocuparte por elegir accidentalmente un nombre de clave que entra en conflicto con los nombres de método de Object. Las operaciones de búsqueda en Map y Set nativos se realizan en tiempo constante, lo que ofrece mejoras de eficiencia sobre lo que es posible con implementaciones simuladas.

En el siguiente ejemplo, se muestra cómo construir un Set y usar for...of para iterar sobre sus elementos:

<pre id="log"></pre>

<script>
    function log() {
    document.querySelector('#log').textContent += Array.prototype.join.call(arguments, '') + '\n';
    }

    log('Creating, using, and iterating over a Set:');
    var randomIntegers = new Set();
    // Generate a random integer in the range [1..10] five times,
    // and use a Set to keep track of the distinct integers that were generated.
    for (var i = 0; i < 5; i++) {
    randomIntegers.add(Math.floor(Math.random() * 10) + 1);
    }
    log(randomIntegers.size, ' distinct integers were generated.');
    log('The number 10 was ', randomIntegers.has(10) ? '' : 'not ', 'one of them.');
    log('Here\'s all of them:');
    // Use for...of to iterate over the items in the Set.
    // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iteration-statements
    // The Set iterator yields a single value corresponding to each entry in the Set.
    for (var item of randomIntegers) {
    log(item);
    }
</script>

A continuación, se muestra una muestra correspondiente en la que se ilustra el uso y la iteración de un Map:

<script>
    log('\nCreating and iterating over a Map:');
    // Maps can be initialized by passing in an iterable value (https://people.mozilla.org/~jorendorff/es6-draft.html#sec-map-iterable)
    // Here, we use an Array of Arrays to initialize. The first value in each sub-Array is the new
    // Map entry's key, and the second is the item's value.
    var typesOfKeys = new Map([
    ['one', 'My key is a string.'],
    ['1', 'My key is also a string'],
    [1, 'My key is a number'],
    [document.querySelector('#log'), 'My key is an object']
    ]);
    // You can also call set() to add new keys/values to an existing Map.
    typesOfKeys.set('!!!!', 'My key is excited!');

    // Use for...of to iterate over the items in the Map.
    // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iteration-statements
    // There are several types of Map iterators available.
    // typesOfKeys.keys() can be used to iterate over just the keys:
    log('Just the keys:');
    for (var key of typesOfKeys.keys()) {
    log('  key: ', key);
    }

    // typesOfKeys.values() can be used to iterate over just the values:
    log('Just the values:');
    for (var value of typesOfKeys.values()) {
    log('  value: ', value);
    }

    // The default Map iterator yields an Array with two items; the first is the Map entry's key and the
    // second is the Map entry's value. This default iterator is equivalent to typesOfKeys.entries().
    log('Keys and values:');
    // Alternative, ES6-idiomatic syntax currently supported in Safari & Firefox:
    // for (var [key, value] of typesOfKeys) { … }
    for (var item of typesOfKeys) {
    log('  ', item[0], ' -> ', item[1]);
    }
</script>

Algunos navegadores, como Chrome, Internet Explorer y Firefox, ya tienen compatibilidad con Set y Map. La compatibilidad nativa con bibliotecas de polyfills, como es6-collections o es6-shim, permiten que los desarrolladores de JavaScript comiencen a crear contenido con estos nuevos tipos de colecciones hoy mismo. No hay polyfills disponibles para la sentencia for...of (aunque se puede transpilar la compatibilidad con Traceur), pero la compatibilidad nativa ya está disponible en Chrome y Firefox.

Actualización, septiembre de 2014: Se vinculó a una opción de polyfill adicional, es6-shim.