-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCollection.js
More file actions
71 lines (71 loc) · 2.44 KB
/
Collection.js
File metadata and controls
71 lines (71 loc) · 2.44 KB
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
/*global Collection: true*/
(function(toExport) {
"use strict";
/**
* Создает оболочка для хранения массива объектов с операциями по извлечению более конкретных элементов
* @class Оболочка для храения массива объектов
*
* @param {Array} элементы коллекции
*/
var Collection = function (otherItems) {
"use strict";
var item;
this.items = [];
for (item in otherItems) {
if (otherItems.hasOwnProperty(item)) {
this.items.push(otherItems[item]);
}
}
};
toExport.Collection = Collection;
/**
* @field {Collection} хранит ссылку на родной конструктор
*/
Collection.prototype.constructor = Collection
/**
* @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj
*
* @return {instanceof this.constructor}
*/
Collection.prototype.add = function (obj) {
var newEvents = this.items.concat([obj]);
return new this.constructor(newEvents);
};
/**
* @function создает новую коллекцию элементов с отфильтрованными элементами
*
* @param {Function} - делегат
*
* @return {instanceof this.constructor}
*/
Collection.prototype.filter = function (selector) {
var newItems = this.items.filter(selector);
return new this.constructor(newItems);
};
/**
* @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj
*
* @param {Function} - компаратор
* @param {Function} - инвертировать, ли результат
*
* @return {instanceof this.constructor}
*/
Collection.prototype.sortBy = function (comparator, isInvert) {
var newItems = [].concat(this.items);
if (newItems.length === 0) {
return [];
}
if (comparator) {
if (isInvert) {
newItems.sort(function (a, b) {
return -1 * comparator(a, b);
});
} else {
newItems.sort(comparator);
}
} else {
newItems.sort();
}
return new this.constructor(newItems);
};
}(window));