-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
325 lines (301 loc) · 8.95 KB
/
index.js
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
const arrayMethods = 'push pop shift unshift splice slice indexOf find findIndex toString map'.split(
/\s+/
);
const cloneMethod = Symbol('clone');
export default function create(...items) {
let subLists = {};
let list;
let subscribers = [];
const filters = {};
const orders = {};
const mappers = {};
function clearListCache() {
Object.keys(subLists).forEach(listName => {
delete subLists[listName].processedItems;
delete subLists[listName].orderedItems;
});
list.length = items.length;
}
function dispatch() {
subscribers.forEach(subscriber => subscriber(items));
}
function modifyItems(callback) {
if (list.__immutable) {
const newItems = items.slice();
callback(newItems);
return createCopy(newItems);
}
clearListCache();
callback(items);
list.length = items.length;
dispatch();
return list;
}
function doFilter(filter, items) {
if (typeof filter === 'string') {
filter = filters[filter];
if (!filter) {
throw new Error(`Filter named ${filter} cannot be found`);
}
}
return items.filter(x => filter(x.item));
}
function doSort(order, items) {
if (typeof order === 'string') {
order = orders[order];
if (!order) {
throw new Error(`Order named ${order} cannot be found`);
}
}
return items.slice().sort((a, b) => {
for (let index = 0; index < order.length; index++) {
const o = order[index];
const getter = o.by;
const aValue = getter(a.item);
const bValue = getter(b.item);
if (aValue > bValue) return o.desc ? -1 : 1;
if (aValue < bValue) return o.desc ? 1 : -1;
}
return 0;
});
}
function createCopy(newItems, meta = {}) {
return create(...newItems)[cloneMethod](
Object.assign(
{
subscribers,
filters,
mappers,
orders,
subLists,
__chainable: list.__chainable,
__immutable: list.__immutable
},
meta
)
);
}
return (list = Object.assign(
arrayMethods.reduce((prototype, method) => {
prototype[method] = function(...args) {
let result;
const listResult = modifyItems(
items => (result = items[method](...args))
);
if (list.__chainable || method === 'push' || method === 'unshift')
return listResult;
return result;
};
return prototype;
}, {}),
{
length: items.length,
[cloneMethod](meta) {
subscribers.push(...meta.subscribers);
Object.assign(filters, meta.filters);
Object.assign(orders, meta.orders);
Object.assign(mappers, meta.mappers);
Object.keys(meta.subLists).forEach(subListName => {
subLists[subListName] = Object.assign(
{
processedItems: undefined,
orderedItems: undefined
},
meta.subLists[subListName]
);
});
list.__chainable = meta.__chainable;
list.__immutable = meta.__immutable;
return list;
},
/**
* update all items which is satisfied predicate
*/
update(predicate, updater, count = 0) {
let updatedItems = 0;
const newItems = items.map((item, index) => {
if (count && updatedItems >= count) return item;
if (predicate(item)) {
updatedItems++;
return updater(item, index);
}
return item;
});
if (updatedItems) {
if (list.__immutable) {
return createCopy(newItems);
}
items = newItems;
clearListCache();
dispatch();
}
return list;
},
/**
* subscribe changed event
*/
subscribe(subscriber) {
subscribers.push(subscriber);
return list.__chainable
? list
: () => (subscribers = subscribers.filter(x => x !== subscriber));
},
/**
* make the list is chainable
*/
chainable(value = true) {
if (list.__chainable === value) return list;
return createCopy(items, {
__chainable: value
});
},
/**
* make the list is immutable
*/
immuatable(value = true) {
if (list.__immutable === value) return list;
return createCopy(items, { __immutable: value });
},
/**
* clone list
*/
clone(includeSubscribers) {
if (includeSubscribers) {
return createCopy(items);
}
return createCopy(items, {
subscribers: []
});
},
/**
* get original items
*/
items() {
return items;
},
/**
* get/set item by its index
*/
item(index, value) {
if (arguments.length === 1) return items[index];
return modifyItems(items => (items[index] = value));
},
removeAll() {
items.splice(0, items.length);
dispatch();
return list;
},
/**
* remove items which is satisfied predicate
*/
remove(predicate, count = 0) {
let removedItems = 0;
const newItems = items.filter(item => {
if (count && removedItems >= count) return true;
if (predicate(item)) {
removedItems++;
return false;
}
return true;
});
if (removedItems) {
if (list.__immutable) {
return createCopy(newItems);
}
items = newItems;
clearListCache();
dispatch();
}
return list;
},
/**
* define sub list with specified options: { filter, order }
*/
define(listName, options = {}) {
const [type, name] = listName.split(':');
if (name) {
switch (type) {
case 'order':
if (options instanceof Function) {
options = { by: options };
}
if (!(options instanceof Array)) {
options = [options];
}
orders[name] = options;
break;
case 'filter':
filters[name] = options;
break;
case 'map':
mappers[name] = options;
break;
default:
throw new Error(`Unsupported option ${type}`);
}
} else {
let { filter, order, map } = options;
if (order && !(order instanceof Array) && typeof order !== 'string') {
order = [order];
}
subLists[listName] = { filter, order, map };
}
return list;
},
/**
* get sub list
* @listName string name defined sub list
* @includeMeta boolean returns array that contains item and its metadata { order: number, item: object, index: number } if true unless returns filtered and sorted items
*/
get(listName = 'default', includeMeta = false) {
let subList = subLists[listName];
if (!subList) {
// create default list with no filter and no order
subLists[listName] = subList = {};
// list name can be combination of predefined filter/order names
if (listName.indexOf(':') !== -1) {
// parse feature list which is separated by spacings
listName.split(/\s+/).forEach(feature => {
// featureType:featureName
const [type, name] = feature.split(/:/);
if (!name) {
// is sub list name, copy all props of referenced sub list to current
Object.assign(subList, subLists[type]);
} else {
subList[type] = name;
}
});
}
}
if (!subList.processedItems) {
const indexedItems = items.map((item, index) => ({ index, item }));
const filteredItems = subList.filter
? doFilter(subList.filter, indexedItems)
: indexedItems;
const orderedItems = subList.order
? doSort(subList.order, filteredItems)
: filteredItems;
orderedItems.forEach((x, index) => (x.order = index));
const mapper = subList.map
? subList.map instanceof Function
? subList.map
: mappers[subList.map]
: undefined;
subList.processedItems = mapper
? filteredItems.map(mapper)
: filteredItems;
subList.orderedItems = orderedItems.map(
(x, ...args) => (mapper ? mapper(x.item, ...args) : x.item)
);
if (subList.extra) {
subList.extraData =
subList.extra(subList.processedItems, subList.orderedItems) || {};
}
}
if (typeof includeMeta === 'string')
return subList.extraData[includeMeta];
return includeMeta ? subList.processedItems : subList.orderedItems;
}
}
));
}