-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathreduce_computed_macros.js
660 lines (546 loc) · 17.5 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
/**
@module ember
@submodule ember-runtime
*/
import { assert } from 'ember-metal/debug';
import { get } from 'ember-metal/property_get';
import EmberError from 'ember-metal/error';
import { ComputedProperty, computed } from 'ember-metal/computed';
import { addObserver, removeObserver } from 'ember-metal/observer';
import compare from 'ember-runtime/compare';
import { isArray } from 'ember-runtime/utils';
import { A as emberA } from 'ember-runtime/system/native_array';
import isNone from 'ember-metal/is_none';
import getProperties from 'ember-metal/get_properties';
function reduceMacro(dependentKey, callback, initialValue) {
return computed(`${dependentKey}.[]`, function() {
let arr = get(this, dependentKey);
if (arr === null || typeof arr !== 'object') { return initialValue; }
return arr.reduce((previousValue, currentValue, index, array) => {
return callback.call(this, previousValue, currentValue, index, array);
}, initialValue);
}).readOnly();
}
function arrayMacro(dependentKey, callback) {
// This is a bit ugly
var propertyName;
if (/@each/.test(dependentKey)) {
propertyName = dependentKey.replace(/\.@each.*$/, '');
} else {
propertyName = dependentKey;
dependentKey += '.[]';
}
return computed(dependentKey, function() {
var value = get(this, propertyName);
if (isArray(value)) {
return emberA(callback.call(this, value));
} else {
return emberA();
}
}).readOnly();
}
function multiArrayMacro(dependentKeys, callback) {
var args = dependentKeys.map(key => `${key}.[]`);
args.push(function() {
return emberA(callback.call(this, dependentKeys));
});
return computed.apply(this, args).readOnly();
}
/**
A computed property that returns the sum of the value
in the dependent array.
@method sum
@for Ember.computed
@param {String} dependentKey
@return {Ember.ComputedProperty} computes the sum of all values in the dependentKey's array
@since 1.4.0
@public
*/
export function sum(dependentKey) {
return reduceMacro(dependentKey, (sum, item) => sum + item, 0);
}
/**
A computed property that calculates the maximum value in the
dependent array. This will return `-Infinity` when the dependent
array is empty.
```javascript
var Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age'),
maxChildAge: Ember.computed.max('childAges')
});
var lordByron = 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 max
@for Ember.computed
@param {String} dependentKey
@return {Ember.ComputedProperty} computes the largest value in the dependentKey's array
@public
*/
export function max(dependentKey) {
return reduceMacro(dependentKey, (max, item) => Math.max(max, item), -Infinity);
}
/**
A computed property that calculates the minimum value in the
dependent array. This will return `Infinity` when the dependent
array is empty.
```javascript
var Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age'),
minChildAge: Ember.computed.min('childAges')
});
var lordByron = 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 min
@for Ember.computed
@param {String} dependentKey
@return {Ember.ComputedProperty} computes the smallest value in the dependentKey's array
@public
*/
export function min(dependentKey) {
return reduceMacro(dependentKey, (min, item) => Math.min(min, item), Infinity);
}
/**
Returns an array mapped via the callback
The callback method you provide should have the following signature.
`item` is the current item in the iteration.
`index` is the integer index of the current item in the iteration.
```javascript
function(item, index);
```
Example
```javascript
var Hamster = Ember.Object.extend({
excitingChores: Ember.computed.map('chores', function(chore, index) {
return chore.toUpperCase() + '!';
})
});
var hamster = Hamster.create({
chores: ['clean', 'write more unit tests']
});
hamster.get('excitingChores'); // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
```
@method map
@for Ember.computed
@param {String} dependentKey
@param {Function} callback
@return {Ember.ComputedProperty} an array mapped via the callback
@public
*/
export function map(dependentKey, callback) {
return arrayMacro(dependentKey, function(value) {
return value.map(callback, this);
});
}
/**
Returns an array mapped to the specified key.
```javascript
var Person = Ember.Object.extend({
childAges: Ember.computed.mapBy('children', 'age')
});
var lordByron = 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 mapBy
@for Ember.computed
@param {String} dependentKey
@param {String} propertyKey
@return {Ember.ComputedProperty} an array mapped to the specified key
@public
*/
export function mapBy(dependentKey, propertyKey) {
assert(
'Ember.computed.mapBy expects a property string for its second argument, ' +
'perhaps you meant to use "map"',
typeof propertyKey === 'string'
);
return map(`${dependentKey}.@each.${propertyKey}`, item => get(item, propertyKey));
}
/**
Filters the array by the callback.
The callback method you provide should have the following signature.
`item` is the current item in the iteration.
`index` is the integer index of the current item in the iteration.
`array` is the dependant array itself.
```javascript
function(item, index, array);
```
```javascript
var Hamster = Ember.Object.extend({
remainingChores: Ember.computed.filter('chores', function(chore, index, array) {
return !chore.done;
})
});
var hamster = Hamster.create({
chores: [
{ name: 'cook', done: true },
{ name: 'clean', done: true },
{ name: 'write more unit tests', done: false }
]
});
hamster.get('remainingChores'); // [{name: 'write more unit tests', done: false}]
```
@method filter
@for Ember.computed
@param {String} dependentKey
@param {Function} callback
@return {Ember.ComputedProperty} the filtered array
@public
*/
export function filter(dependentKey, callback) {
return arrayMacro(dependentKey, function(value) {
return value.filter(callback, this);
});
}
/**
Filters the array by the property and value
```javascript
var Hamster = Ember.Object.extend({
remainingChores: Ember.computed.filterBy('chores', 'done', false)
});
var hamster = Hamster.create({
chores: [
{ name: 'cook', done: true },
{ name: 'clean', done: true },
{ name: 'write more unit tests', done: false }
]
});
hamster.get('remainingChores'); // [{ name: 'write more unit tests', done: false }]
```
@method filterBy
@for Ember.computed
@param {String} dependentKey
@param {String} propertyKey
@param {*} value
@return {Ember.ComputedProperty} the filtered array
@public
*/
export function filterBy(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 filter(`${dependentKey}.@each.${propertyKey}`, callback);
}
/**
A computed property which returns a new array with all the unique
elements from one or more dependent arrays.
Example
```javascript
var Hamster = Ember.Object.extend({
uniqueFruits: Ember.computed.uniq('fruits')
});
var hamster = Hamster.create({
fruits: [
'banana',
'grape',
'kale',
'banana'
]
});
hamster.get('uniqueFruits'); // ['banana', 'grape', 'kale']
```
@method uniq
@for Ember.computed
@param {String} propertyKey*
@return {Ember.ComputedProperty} computes a new array with all the
unique elements from the dependent array
@public
*/
export function uniq(...args) {
return multiArrayMacro(args, function(dependentKeys) {
var uniq = emberA();
dependentKeys.forEach(dependentKey => {
var value = get(this, dependentKey);
if (isArray(value)) {
value.forEach(item => {
if (uniq.indexOf(item) === -1) {
uniq.push(item);
}
});
}
});
return uniq;
});
}
/**
Alias for [Ember.computed.uniq](/api/#method_computed_uniq).
@method union
@for Ember.computed
@param {String} propertyKey*
@return {Ember.ComputedProperty} computes a new array with all the
unique elements from the dependent array
@public
*/
export var union = uniq;
/**
A computed property which returns a new array with all the duplicated
elements from two or more dependent arrays.
Example
```javascript
var obj = Ember.Object.extend({
friendsInCommon: Ember.computed.intersect('adaFriends', 'charlesFriends')
}).create({
adaFriends: ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'],
charlesFriends: ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock']
});
obj.get('friendsInCommon'); // ['William King', 'Mary Somerville']
```
@method intersect
@for Ember.computed
@param {String} propertyKey*
@return {Ember.ComputedProperty} computes a new array with all the
duplicated elements from the dependent arrays
@public
*/
export function intersect(...args) {
return multiArrayMacro(args, function(dependentKeys) {
var arrays = dependentKeys.map(dependentKey => {
var array = get(this, dependentKey);
return isArray(array) ? array : [];
});
var results = arrays.pop().filter(candidate => {
for (var i = 0; i < arrays.length; i++) {
var found = false;
var array = arrays[i];
for (var j = 0; j < array.length; j++) {
if (array[j] === candidate) {
found = true;
break;
}
}
if (found === false) { return false; }
}
return true;
});
return emberA(results);
});
}
/**
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
var Hamster = Ember.Object.extend({
likes: ['banana', 'grape', 'kale'],
wants: Ember.computed.setDiff('likes', 'fruits')
});
var hamster = Hamster.create({
fruits: [
'grape',
'kale',
]
});
hamster.get('wants'); // ['banana']
```
@method setDiff
@for Ember.computed
@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
@public
*/
export function setDiff(setAProperty, setBProperty) {
if (arguments.length !== 2) {
throw new EmberError('setDiff requires exactly two dependent arrays.');
}
return computed(`${setAProperty}.[]`, `${setBProperty}.[]`, function() {
var setA = this.get(setAProperty);
var setB = this.get(setBProperty);
if (!isArray(setA)) { return emberA(); }
if (!isArray(setB)) { return emberA(setA); }
return setA.filter(x => setB.indexOf(x) === -1);
}).readOnly();
}
/**
A computed property that returns the array of values
for the provided dependent properties.
Example
```javascript
var Hamster = Ember.Object.extend({
clothes: Ember.computed.collect('hat', 'shirt')
});
var hamster = Hamster.create();
hamster.get('clothes'); // [null, null]
hamster.set('hat', 'Camp Hat');
hamster.set('shirt', 'Camp Shirt');
hamster.get('clothes'); // ['Camp Hat', 'Camp Shirt']
```
@method collect
@for Ember.computed
@param {String} dependentKey*
@return {Ember.ComputedProperty} computed property which maps
values of all passed in properties to an array.
@public
*/
export function collect(...dependentKeys) {
return multiArrayMacro(dependentKeys, function() {
var properties = getProperties(this, dependentKeys);
var res = emberA();
for (var key in properties) {
if (properties.hasOwnProperty(key)) {
if (isNone(properties[key])) {
res.push(null);
} else {
res.push(properties[key]);
}
}
}
return res;
});
}
/**
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 negative number (e.g. `-1`) when `itemA` should come before
`itemB`. It should return positive number (e.g. `1`) when `itemA` should come after
`itemB`. If the `itemA` and `itemB` are equal this function should return `0`.
Therefore, if this function is comparing some numeric values, simple `itemA - itemB` or
`itemA.get( 'foo' ) - itemB.get( 'foo' )` can be used instead of series of `if`.
Example
```javascript
var ToDoList = Ember.Object.extend({
// using standard ascending sort
todosSorting: ['name'],
sortedTodos: Ember.computed.sort('todos', 'todosSorting'),
// using descending sort
todosSortingDesc: ['name:desc'],
sortedTodosDesc: Ember.computed.sort('todos', 'todosSortingDesc'),
// using a custom sort function
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('sortedTodosDesc'); // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }]
todoList.get('priorityTodos'); // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]
```
@method sort
@for Ember.computed
@param {String} itemsKey
@param {String or Function} sortDefinition a dependent key to an
array of sort properties (add `:desc` to the arrays sort properties to sort descending) or a function to use when sorting
@return {Ember.ComputedProperty} computes a new sorted array based
on the sort property array or callback function
@public
*/
export function sort(itemsKey, sortDefinition) {
assert(
'Ember.computed.sort requires two arguments: an array key to sort and ' +
'either a sort properties key or sort function',
arguments.length === 2
);
if (typeof sortDefinition === 'function') {
return customSort(itemsKey, sortDefinition);
} else {
return propertySort(itemsKey, sortDefinition);
}
}
function customSort(itemsKey, comparator) {
return arrayMacro(itemsKey, function(value) {
return value.slice().sort((x, y) => comparator.call(this, x, y));
});
}
// This one needs to dynamically set up and tear down observers on the itemsKey
// depending on the sortProperties
function propertySort(itemsKey, sortPropertiesKey) {
var cp = new ComputedProperty(function(key) {
function didChange() {
this.notifyPropertyChange(key);
}
var items = itemsKey === '@this' ? this : get(this, itemsKey);
var sortProperties = get(this, sortPropertiesKey);
if (items === null || typeof items !== 'object') { return emberA(); }
// TODO: Ideally we'd only do this if things have changed
if (cp._sortPropObservers) {
cp._sortPropObservers.forEach(args => removeObserver.apply(null, args));
}
cp._sortPropObservers = [];
if (!isArray(sortProperties)) { return items; }
// Normalize properties
var normalizedSort = sortProperties.map(p => {
let [prop, direction] = p.split(':');
direction = direction || 'asc';
return [prop, direction];
});
// TODO: Ideally we'd only do this if things have changed
// Add observers
normalizedSort.forEach(prop => {
var args = [this, `${itemsKey}.@each.${prop[0]}`, didChange];
cp._sortPropObservers.push(args);
addObserver.apply(null, args);
});
return emberA(items.slice().sort((itemA, itemB) => {
for (var i = 0; i < normalizedSort.length; ++i) {
var [prop, direction] = normalizedSort[i];
var result = compare(get(itemA, prop), get(itemB, prop));
if (result !== 0) {
return (direction === 'desc') ? (-1 * result) : result;
}
}
return 0;
}));
});
return cp.property(`${itemsKey}.[]`, `${sortPropertiesKey}.[]`).readOnly();
}