K
K
Konstantin Kitmanov2015-03-30 20:35:30
JavaScript
Konstantin Kitmanov, 2015-03-30 20:35:30

Backbone.Collection and Symbol.iterator, how to do better?

ES2015 aka ES6 aka Harmony is coming. It's time to practice on home projects!
There is a ready-made function that takes an array of objects of the form {entities: []} as input and iterates over them, like this:

function iterateEntities (arr, iterator) {
    for (let item of arr) {
        for (let [index, entity] of item.entities.entries()) {
            iterator(entity, index, item);
        }
    }
}

I want to iterate over the models of the collection, as if they are exactly the same plain objects, in order to use this function.
It turned out like this:
'use strict';

import Skull from 'backbone-skull';

function collectionIterator (models) {
    return  {
        _i: -1,
        next: function () {
            return {
                value: models[this._i + 1].attributes,
                done: models.length - 1 === ++this._i
            }
        }
    }
}

class CollectionAbstract extends Skull.Collection {
    [Symbol.iterator] () {
        	return collectionIterator(this.models);
    }
}

export default CollectionAbstract;

Tests show that it works as intended, but somehow inelegant. Is it possible to somehow prettier, without these here ++this._i? I don't understand generators well, maybe it will be better with them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2015-04-01
@k12th

The correct answer is, indeed, generators :

function* collectionIterator (models) {
    for (let model of models) {
        yield model.attributes;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question