File size: 1,420 Bytes
e7c953d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'use strict';

function BaseCollection() {
    //Nothing to do
}

BaseCollection.prototype = Object.create(Array.prototype);

BaseCollection.prototype.maxLength = Infinity;

BaseCollection.prototype.add = function(item) {
    if (!item || this.findWhere({id: item.id}) !== undefined) return false;
    this.push(item);
    if (this.length > this.maxLength) this.shift();
    return true;
};

BaseCollection.prototype.where = function(attrs) {
    var keys = Object.keys(attrs),
        results = [];

    for (var itemIndex = 0; itemIndex < this.length; itemIndex++) {
        for (var itemKey = 0; itemKey < keys.length; itemKey++) {
            if (this[itemIndex][keys[itemKey]] !== attrs[keys[itemKey]]) break;
            if (itemKey === keys.length - 1) results.push(this[itemIndex]);
        }
    }

    return results;
};

BaseCollection.prototype.findWhere = function(attrs) {
    return this.where(attrs)[0];
};

BaseCollection.prototype.remove = function(item) {
    if (!item || this.findWhere({id: item.id}) === undefined) return false;

    for (var itemIndex = 0; itemIndex < this.length; itemIndex++) {
        if (this[itemIndex].id !== item.id) continue;
        this.splice(itemIndex, 1);
        break;
    }

    return true;
};

BaseCollection.prototype.clear = function() {
    this.splice(0, this.length);
};

module.exports = BaseCollection;