Raccolta e iterazione alla maniera di ES6

Anche se è ancora in bozza, la specifica ECMAScript 6 promette molti nuovi ed entusiasmanti strumenti da aggiungere alla cintura di programmazione JavaScript. Nuove classi come Set e Map offrono soluzioni native per lavorare con tipi specifici di raccolte e l'istruzione for...of offre un'alternativa elegante ai metodi tradizionali per eseguire l'iterazione dei dati.

Gli Set offrono un modo per tenere traccia di una raccolta di elementi in cui ogni elemento può apparire al massimo una volta. Gli elementi Map offrono più funzionalità rispetto a quelle offerte in precedenza utilizzando i Object per associare le chiavi ai valori. Con un elemento Map, le chiavi non devono essere necessariamente stringhe e non devi preoccuparti di scegliere accidentalmente un nome chiave che sia in conflitto con i nomi dei metodi di Object. Le operazioni di ricerca su Map e Set nativi vengono eseguite in tempo costante, il che offre miglioramenti in termini di efficienza rispetto a quanto possibile con implementazioni simulate.

Il seguente esempio mostra la creazione di un elemento Set e l'utilizzo di for...of per eseguire l'iterazione sui suoi elementi:

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

Ecco un esempio corrispondente che illustra l'utilizzo e l'iterazione di 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>

Alcuni browser, come Chrome, Internet Explorer e Firefox, hanno già aggiunto il supporto per Set e Map. Il supporto nativo integrato da librerie di polyfill come es6-collections o es6-shim significa che gli sviluppatori JavaScript possono iniziare a creare con questi nuovi tipi di raccolte oggi stesso. Non sono disponibili polyfill per l'istruzione for...of (anche se è possibile eseguire il transpile del supporto tramite Traceur), tuttavia il supporto nativo è oggi disponibile in Chrome e Firefox.

Aggiornamento, settembre 2014: collegamento a un'opzione aggiuntiva di polyfill, es6-shim.