-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
reduce_computed_macros.js
700 lines (574 loc) · 19.8 KB
/
reduce_computed_macros.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
require('ember-runtime/computed/array_computed');
/**
@module ember
@submodule ember-runtime
*/
var get = Ember.get,
set = Ember.set,
guidFor = Ember.guidFor,
merge = Ember.merge,
a_slice = [].slice,
forEach = Ember.EnumerableUtils.forEach,
map = Ember.EnumerableUtils.map;
/**
A computed property that calculates the maximum value in the
dependent array. This will return `-Infinity` when the dependent
array is empty.
Example
```javascript
App.Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age'),
maxChildAge: Ember.computed.max('childAges')
});
var lordByron = App.Person.create({children: []});
lordByron.get('maxChildAge'); // -Infinity
lordByron.get('children').pushObject({name: 'Augusta Ada Byron', age: 7});
lordByron.get('maxChildAge'); // 7
lordByron.get('children').pushObjects([{name: 'Allegra Byron', age: 5}, {name: 'Elizabeth Medora Leigh', age: 8}]);
lordByron.get('maxChildAge'); // 8
```
@method computed.max
@for Ember
@param {String} dependentKey
@return {Ember.ComputedProperty} computes the largest value in the dependentKey's array
*/
Ember.computed.max = function (dependentKey) {
return Ember.reduceComputed.call(null, dependentKey, {
initialValue: -Infinity,
addedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
return Math.max(accumulatedValue, item);
},
removedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
if (item < accumulatedValue) {
return accumulatedValue;
}
}
});
};
/**
A computed property that calculates the minimum value in the
dependent array. This will return `Infinity` when the dependent
array is empty.
Example
```javascript
App.Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age'),
minChildAge: Ember.computed.min('childAges')
});
var lordByron = App.Person.create({children: []});
lordByron.get('minChildAge'); // Infinity
lordByron.get('children').pushObject({name: 'Augusta Ada Byron', age: 7});
lordByron.get('minChildAge'); // 7
lordByron.get('children').pushObjects([{name: 'Allegra Byron', age: 5}, {name: 'Elizabeth Medora Leigh', age: 8}]);
lordByron.get('minChildAge'); // 5
```
@method computed.min
@for Ember
@param {String} dependentKey
@return {Ember.ComputedProperty} computes the smallest value in the dependentKey's array
*/
Ember.computed.min = function (dependentKey) {
return Ember.reduceComputed.call(null, dependentKey, {
initialValue: Infinity,
addedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
return Math.min(accumulatedValue, item);
},
removedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
if (item > accumulatedValue) {
return accumulatedValue;
}
}
});
};
/**
Returns an array mapped via the callback
The callback method you provide should have the following signature:
```javascript
function(item);
```
- `item` is the current item in the iteration.
Example
```javascript
App.Hampster = Ember.Object.extend({
excitingChores: Ember.computed.map('chores', function(chore) {
return chore.toUpperCase() + '!';
})
});
var hampster = App.Hampster.create({chores: ['cook', 'clean', 'write more unit tests']});
hampster.get('excitingChores'); // ['COOK!', 'CLEAN!', 'WRITE MORE UNIT TESTS!']
```
@method computed.map
@for Ember
@param {String} dependentKey
@param {Function} callback
@return {Ember.ComputedProperty} an array mapped via the callback
*/
Ember.computed.map = function(dependentKey, callback) {
var options = {
addedItem: function(array, item, changeMeta, instanceMeta) {
var mapped = callback.call(this, item);
array.insertAt(changeMeta.index, mapped);
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
array.removeAt(changeMeta.index, 1);
return array;
}
};
return Ember.arrayComputed(dependentKey, options);
};
/**
Returns an array mapped to the specified key.
Example
```javascript
App.Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age')
});
var lordByron = App.Person.create({children: []});
lordByron.get('childAges'); // []
lordByron.get('children').pushObject({name: 'Augusta Ada Byron', age: 7});
lordByron.get('childAges'); // [7]
lordByron.get('children').pushObjects([{name: 'Allegra Byron', age: 5}, {name: 'Elizabeth Medora Leigh', age: 8}]);
lordByron.get('childAges'); // [7, 5, 8]
```
@method computed.mapBy
@for Ember
@param {String} dependentKey
@param {String} propertyKey
@return {Ember.ComputedProperty} an array mapped to the specified key
*/
Ember.computed.mapBy = function(dependentKey, propertyKey) {
var callback = function(item) { return get(item, propertyKey); };
return Ember.computed.map(dependentKey + '.@each.' + propertyKey, callback);
};
/**
@method computed.mapProperty
@for Ember
@deprecated Use `Ember.computed.mapBy` instead
@param dependentKey
@param propertyKey
*/
Ember.computed.mapProperty = Ember.computed.mapBy;
/**
Filters the array by the callback.
The callback method you provide should have the following signature:
```javascript
function(item);
```
- `item` is the current item in the iteration.
Example
```javascript
App.Hampster = Ember.Object.extend({
remainingChores: Ember.computed.filter('chores', function(chore) {
return !chore.done;
})
});
var hampster = App.Hampster.create({chores: [
{name: 'cook', done: true},
{name: 'clean', done: true},
{name: 'write more unit tests', done: false}
]});
hampster.get('remainingChores'); // [{name: 'write more unit tests', done: false}]
```
@method computed.filter
@for Ember
@param {String} dependentKey
@param {Function} callback
@return {Ember.ComputedProperty} the filtered array
*/
Ember.computed.filter = function(dependentKey, callback) {
var options = {
initialize: function (array, changeMeta, instanceMeta) {
instanceMeta.filteredArrayIndexes = new Ember.SubArray();
},
addedItem: function(array, item, changeMeta, instanceMeta) {
var match = !!callback.call(this, item),
filterIndex = instanceMeta.filteredArrayIndexes.addItem(changeMeta.index, match);
if (match) {
array.insertAt(filterIndex, item);
}
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
var filterIndex = instanceMeta.filteredArrayIndexes.removeItem(changeMeta.index);
if (filterIndex > -1) {
array.removeAt(filterIndex);
}
return array;
}
};
return Ember.arrayComputed(dependentKey, options);
};
/**
Filters the array by the property and value
Example
```javascript
App.Hampster = Ember.Object.extend({
remainingChores: Ember.computed.filterBy('chores', 'done', false)
});
var hampster = App.Hampster.create({chores: [
{name: 'cook', done: true},
{name: 'clean', done: true},
{name: 'write more unit tests', done: false}
]});
hampster.get('remainingChores'); // [{name: 'write more unit tests', done: false}]
```
@method computed.filterBy
@for Ember
@param {String} dependentKey
@param {String} propertyKey
@param {String} value
@return {Ember.ComputedProperty} the filtered array
*/
Ember.computed.filterBy = function(dependentKey, propertyKey, value) {
var callback;
if (arguments.length === 2) {
callback = function(item) {
return get(item, propertyKey);
};
} else {
callback = function(item) {
return get(item, propertyKey) === value;
};
}
return Ember.computed.filter(dependentKey + '.@each.' + propertyKey, callback);
};
/**
@method computed.filterProperty
@for Ember
@param dependentKey
@param propertyKey
@param value
@deprecated Use `Ember.computed.filterBy` instead
*/
Ember.computed.filterProperty = Ember.computed.filterBy;
/**
A computed property which returns a new array with all the unique
elements from one or more dependent arrays.
Example
```javascript
App.Hampster = Ember.Object.extend({
uniqueFruits: Ember.computed.uniq('fruits')
});
var hampster = App.Hampster.create({fruits: [
'banana',
'grape',
'kale',
'banana'
]});
hampster.get('uniqueFruits'); // ['banana', 'grape', 'kale']
```
@method computed.uniq
@for Ember
@param {String} propertyKey*
@return {Ember.ComputedProperty} computes a new array with all the
unique elements from the dependent array
*/
Ember.computed.uniq = function() {
var args = a_slice.call(arguments);
args.push({
initialize: function(array, changeMeta, instanceMeta) {
instanceMeta.itemCounts = {};
},
addedItem: function(array, item, changeMeta, instanceMeta) {
var guid = guidFor(item);
if (!instanceMeta.itemCounts[guid]) {
instanceMeta.itemCounts[guid] = 1;
} else {
++instanceMeta.itemCounts[guid];
}
array.addObject(item);
return array;
},
removedItem: function(array, item, _, instanceMeta) {
var guid = guidFor(item),
itemCounts = instanceMeta.itemCounts;
if (--itemCounts[guid] === 0) {
array.removeObject(item);
}
return array;
}
});
return Ember.arrayComputed.apply(null, args);
};
/**
Alias for [Ember.computed.uniq](/api/#method_computed_uniq).
@method computed.union
@for Ember
@param {String} propertyKey*
@return {Ember.ComputedProperty} computes a new array with all the
unique elements from the dependent array
*/
Ember.computed.union = Ember.computed.uniq;
/**
A computed property which returns a new array with all the duplicated
elements from two or more dependeny arrays.
Example
```javascript
var obj = Ember.Object.createWithMixins({
adaFriends: ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'],
charlesFriends: ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock'],
friendsInCommon: Ember.computed.intersect('adaFriends', 'charlesFriends')
});
obj.get('friendsInCommon'); // ['William King', 'Mary Somerville']
```
@method computed.intersect
@for Ember
@param {String} propertyKey*
@return {Ember.ComputedProperty} computes a new array with all the
duplicated elements from the dependent arrays
*/
Ember.computed.intersect = function () {
var getDependentKeyGuids = function (changeMeta) {
return map(changeMeta.property._dependentKeys, function (dependentKey) {
return guidFor(dependentKey);
});
};
var args = a_slice.call(arguments);
args.push({
initialize: function (array, changeMeta, instanceMeta) {
instanceMeta.itemCounts = {};
},
addedItem: function(array, item, changeMeta, instanceMeta) {
var itemGuid = guidFor(item),
dependentGuids = getDependentKeyGuids(changeMeta),
dependentGuid = guidFor(changeMeta.arrayChanged),
numberOfDependentArrays = changeMeta.property._dependentKeys.length,
itemCounts = instanceMeta.itemCounts;
if (!itemCounts[itemGuid]) { itemCounts[itemGuid] = {}; }
if (itemCounts[itemGuid][dependentGuid] === undefined) { itemCounts[itemGuid][dependentGuid] = 0; }
if (++itemCounts[itemGuid][dependentGuid] === 1 &&
numberOfDependentArrays === Ember.keys(itemCounts[itemGuid]).length) {
array.addObject(item);
}
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
var itemGuid = guidFor(item),
dependentGuids = getDependentKeyGuids(changeMeta),
dependentGuid = guidFor(changeMeta.arrayChanged),
numberOfDependentArrays = changeMeta.property._dependentKeys.length,
numberOfArraysItemAppearsIn,
itemCounts = instanceMeta.itemCounts;
if (itemCounts[itemGuid][dependentGuid] === undefined) { itemCounts[itemGuid][dependentGuid] = 0; }
if (--itemCounts[itemGuid][dependentGuid] === 0) {
delete itemCounts[itemGuid][dependentGuid];
numberOfArraysItemAppearsIn = Ember.keys(itemCounts[itemGuid]).length;
if (numberOfArraysItemAppearsIn === 0) {
delete itemCounts[itemGuid];
}
array.removeObject(item);
}
return array;
}
});
return Ember.arrayComputed.apply(null, args);
};
/**
A computed property which returns a new array with all the
properties from the first dependent array that are not in the second
dependent array.
Example
```javascript
App.Hampster = Ember.Object.extend({
likes: ['banana', 'grape', 'kale'],
wants: Ember.computed.setDiff('likes', 'fruits')
});
var hampster = App.Hampster.create({fruits: [
'grape',
'kale',
]});
hampster.get('wants'); // ['banana']
```
@method computed.setDiff
@for Ember
@param {String} setAProperty
@param {String} setBProperty
@return {Ember.ComputedProperty} computes a new array with all the
items from the first dependent array that are not in the second
dependent array
*/
Ember.computed.setDiff = function (setAProperty, setBProperty) {
if (arguments.length !== 2) {
throw new Error("setDiff requires exactly two dependent arrays.");
}
return Ember.arrayComputed.call(null, setAProperty, setBProperty, {
addedItem: function (array, item, changeMeta, instanceMeta) {
var setA = get(this, setAProperty),
setB = get(this, setBProperty);
if (changeMeta.arrayChanged === setA) {
if (!setB.contains(item)) {
array.addObject(item);
}
} else {
array.removeObject(item);
}
return array;
},
removedItem: function (array, item, changeMeta, instanceMeta) {
var setA = get(this, setAProperty),
setB = get(this, setBProperty);
if (changeMeta.arrayChanged === setB) {
if (setA.contains(item)) {
array.addObject(item);
}
} else {
array.removeObject(item);
}
return array;
}
});
};
function binarySearch(array, item, low, high) {
var mid, midItem, res, guidMid, guidItem;
if (arguments.length < 4) { high = get(array, 'length'); }
if (arguments.length < 3) { low = 0; }
if (low === high) {
return low;
}
mid = low + Math.floor((high - low) / 2);
midItem = array.objectAt(mid);
guidMid = _guidFor(midItem);
guidItem = _guidFor(item);
if (guidMid === guidItem) {
return mid;
}
res = this.order(midItem, item);
if (res === 0) {
res = guidMid < guidItem ? -1 : 1;
}
if (res < 0) {
return this.binarySearch(array, item, mid+1, high);
} else if (res > 0) {
return this.binarySearch(array, item, low, mid);
}
return mid;
function _guidFor(item) {
if (Ember.ObjectProxy.detectInstance(item)) {
return guidFor(get(item, 'content'));
}
return guidFor(item);
}
}
/**
A computed property which returns a new array with all the
properties from the first dependent array sorted based on a property
or sort function.
The callback method you provide should have the following signature:
```javascript
function(itemA, itemB);
```
- `itemA` the first item to compare.
- `itemB` the second item to compare.
This function should return `-1` when `itemA` should come before
`itemB`. It should return `1` when `itemA` should come after
`itemB`. If the `itemA` and `itemB` are equal this function should return `0`.
Example
```javascript
var ToDoList = Ember.Object.extend({
todosSorting: ['name'],
sortedTodos: Ember.computed.sort('todos', 'todosSorting'),
priorityTodos: Ember.computed.sort('todos', function(a, b){
if (a.priority > b.priority) {
return 1;
} else if (a.priority < b.priority) {
return -1;
}
return 0;
}),
});
var todoList = ToDoList.create({todos: [
{name: 'Unit Test', priority: 2},
{name: 'Documentation', priority: 3},
{name: 'Release', priority: 1}
]});
todoList.get('sortedTodos'); // [{name:'Documentation', priority:3}, {name:'Release', priority:1}, {name:'Unit Test', priority:2}]
todoList.get('priorityTodos'); // [{name:'Release', priority:1}, {name:'Unit Test', priority:2}, {name:'Documentation', priority:3}]
```
@method computed.sort
@for Ember
@param {String} dependentKey
@param {String or Function} sortDefinition a dependent key to an
array of sort properties or a function to use when sorting
@return {Ember.ComputedProperty} computes a new sorted array based
on the sort property array or callback function
*/
Ember.computed.sort = function (itemsKey, sortDefinition) {
Ember.assert("Ember.computed.sort requires two arguments: an array key to sort and either a sort properties key or sort function", arguments.length === 2);
var initFn, sortPropertiesKey;
if (typeof sortDefinition === 'function') {
initFn = function (array, changeMeta, instanceMeta) {
instanceMeta.order = sortDefinition;
instanceMeta.binarySearch = binarySearch;
};
} else {
sortPropertiesKey = sortDefinition;
initFn = function (array, changeMeta, instanceMeta) {
function setupSortProperties() {
var sortPropertyDefinitions = get(this, sortPropertiesKey),
sortProperty,
sortProperties = instanceMeta.sortProperties = [],
sortPropertyAscending = instanceMeta.sortPropertyAscending = {},
idx,
asc;
Ember.assert("Cannot sort: '" + sortPropertiesKey + "' is not an array.", Ember.isArray(sortPropertyDefinitions));
changeMeta.property.clearItemPropertyKeys(itemsKey);
forEach(sortPropertyDefinitions, function (sortPropertyDefinition) {
if ((idx = sortPropertyDefinition.indexOf(':')) !== -1) {
sortProperty = sortPropertyDefinition.substring(0, idx);
asc = sortPropertyDefinition.substring(idx+1).toLowerCase() !== 'desc';
} else {
sortProperty = sortPropertyDefinition;
asc = true;
}
sortProperties.push(sortProperty);
sortPropertyAscending[sortProperty] = asc;
changeMeta.property.itemPropertyKey(itemsKey, sortProperty);
});
sortPropertyDefinitions.addObserver('@each', this, updateSortPropertiesOnce);
}
function updateSortPropertiesOnce() {
Ember.run.once(this, updateSortProperties, changeMeta.propertyName);
}
function updateSortProperties(propertyName) {
setupSortProperties.call(this);
changeMeta.property.recomputeOnce.call(this, propertyName);
}
Ember.addObserver(this, sortPropertiesKey, updateSortPropertiesOnce);
setupSortProperties.call(this);
instanceMeta.order = function (itemA, itemB) {
var sortProperty, result, asc;
for (var i = 0; i < this.sortProperties.length; ++i) {
sortProperty = this.sortProperties[i];
result = Ember.compare(get(itemA, sortProperty), get(itemB, sortProperty));
if (result !== 0) {
asc = this.sortPropertyAscending[sortProperty];
return asc ? result : (-1 * result);
}
}
return 0;
};
instanceMeta.binarySearch = binarySearch;
};
}
return Ember.arrayComputed.call(null, itemsKey, {
initialize: initFn,
addedItem: function (array, item, changeMeta, instanceMeta) {
var index = instanceMeta.binarySearch(array, item);
array.insertAt(index, item);
return array;
},
removedItem: function (array, item, changeMeta, instanceMeta) {
var proxyProperties, index, searchItem;
if (changeMeta.previousValues) {
proxyProperties = merge({ content: item }, changeMeta.previousValues);
searchItem = Ember.ObjectProxy.create(proxyProperties);
} else {
searchItem = item;
}
index = instanceMeta.binarySearch(array, searchItem);
array.removeAt(index);
return array;
}
});
};