File size: 2,229 Bytes
4b876a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
function Collection() {
  var items = [];

  var self = {
    add: function add(item) {
      items.push(item);
    },

    insert: function insert(index, item) {
      items.splice(index, 0, item);
    },

    removeAtIndex: function removeAtIndex(index) {
      items.splice(index, 1);
    },

    unshift: function unshift(item) {
      items.unshift(item);
    },

    shift: function shift() {
      return items.shift();
    },

    clear: function clear() {
      items.length = 0;
    },

    indexOf: function indexOf(item) {
      return items.indexOf(item);
    },

    getAtIndex: function getAtIndex(index) {
      return items[index];
    },

    getLast: function getLast() {
      return items[items.length - 1];
    },

    forEach: function forEach(userFunction) {
      var itemsCopy = items.slice(0);
      itemsCopy.forEach(userFunction);
    },

    asyncForEach: function asyncForEach(userFunction, callback) {
      var itemsCopy = items.slice(0);

      function iterate() {
        if (itemsCopy.length > 0) {
          processItem();
        } else {
          callback();
        }
      }

      function processItem() {
        var item = itemsCopy.shift();
        userFunction(item, function () {
          iterate();
        });
      }

      iterate();
    },

    syncMap: function map(userFunction) {
      var newCollection = new Collection();
      items.map(function (item) {
        newCollection.add(userFunction(item));
      });
      return newCollection;
    },

    sort: function sort(comparator) {
      var sortedItems = items.sort(comparator);
      var sortedCollection = new Collection();
      sortedItems.forEach(function (item) {
        sortedCollection.add(item);
      });
      return sortedCollection;
    },

    length: function length() {
      return items.length;
    },

    toArray: function toArray() {
      return items.slice(0);
    },

    filter: function (predicate) {
      var filteredItems = items.filter(predicate);
      var filteredCollection = new Collection();
      filteredItems.forEach(function (item) {
        filteredCollection.add(item);
      });
      return filteredCollection;
    }
  };
  return self;
}

module.exports = Collection;