-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
array_events.ts
94 lines (78 loc) · 2.49 KB
/
array_events.ts
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
import { peekMeta } from '@ember/-internals/meta';
import { EMBER_METAL_TRACKED_PROPERTIES } from '@ember/canary-features';
import { peekCacheFor } from './computed_cache';
import { eachProxyArrayDidChange, eachProxyArrayWillChange } from './each_proxy_events';
import { sendEvent } from './events';
import { notifyPropertyChange } from './property_events';
export function arrayContentWillChange<T extends object>(
array: T,
startIdx: number,
removeAmt: number,
addAmt: number
): T {
// if no args are passed assume everything changes
if (startIdx === undefined) {
startIdx = 0;
removeAmt = addAmt = -1;
} else {
if (removeAmt === undefined) {
removeAmt = -1;
}
if (addAmt === undefined) {
addAmt = -1;
}
}
if (!EMBER_METAL_TRACKED_PROPERTIES) {
eachProxyArrayWillChange(array, startIdx, removeAmt, addAmt);
}
sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]);
return array;
}
export function arrayContentDidChange<T extends { length: number }>(
array: T,
startIdx: number,
removeAmt: number,
addAmt: number
): T {
// if no args are passed assume everything changes
if (startIdx === undefined) {
startIdx = 0;
removeAmt = addAmt = -1;
} else {
if (removeAmt === undefined) {
removeAmt = -1;
}
if (addAmt === undefined) {
addAmt = -1;
}
}
let meta = peekMeta(array);
if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) {
notifyPropertyChange(array, 'length', meta);
}
notifyPropertyChange(array, '[]', meta);
if (!EMBER_METAL_TRACKED_PROPERTIES) {
eachProxyArrayDidChange(array, startIdx, removeAmt, addAmt);
}
sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]);
let cache = peekCacheFor(array);
if (cache !== undefined) {
let length = array.length;
let addedAmount = addAmt === -1 ? 0 : addAmt;
let removedAmount = removeAmt === -1 ? 0 : removeAmt;
let delta = addedAmount - removedAmount;
let previousLength = length - delta;
let normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx;
if (cache.has('firstObject') && normalStartIdx === 0) {
notifyPropertyChange(array, 'firstObject', meta);
}
if (cache.has('lastObject')) {
let previousLastIndex = previousLength - 1;
let lastAffectedIndex = normalStartIdx + removedAmount;
if (previousLastIndex < lastAffectedIndex) {
notifyPropertyChange(array, 'lastObject', meta);
}
}
}
return array;
}