-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubjectArray.ts
67 lines (52 loc) · 1.52 KB
/
SubjectArray.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
type MethodName = 'Set' | 'Remove' | 'Push' | 'Clear';
export class SubjectArray<T> {
private _arr: T[] = [];
private _callbacks = { Push: [], Remove: [], Set: [], Clear: [] };
private _originalArray: SubjectArray<T>;
private _mapFunc: Function;
constructor(arr?: Array<T>) {
this._arr = arr || [];
}
public Get(index: number): T {
return this._arr[index];
}
public Set(index: number, item: T): void {
this._arr[index] = item;
let callbacks = this._callbacks.Set;
if (callbacks.length > 0)
callbacks.forEach(x => x(index, item));
}
public Remove(index: number): void {
this._arr.splice(index, 1);
let callbacks = this._callbacks.Remove;
if (callbacks.length > 0)
callbacks.forEach(x => x(index));
}
public Map<U>(func: (item: T) => any): SubjectArray<U> {
let list = new SubjectArray<any>(this._arr.map(func));
list._originalArray = this;
list._mapFunc = func;
return list;
}
public Push(item: T): void {
this._arr.push(item);
let callbacks = this._callbacks.Push;
if (callbacks.length > 0)
callbacks.forEach(x => x(item));
}
public ForEach(func: (item: T) => void): void {
this._arr.forEach(func);
}
public Clear(): void {
this._arr = [];
let callbacks = this._callbacks.Clear;
if (callbacks.length > 0)
callbacks.forEach(x => x());
}
public AddCallbackToOriginalSubjectArray(methodName: MethodName, func: Function): void {
this._originalArray._callbacks[methodName.toString()].push(func);
}
public ExecuteMapFunction(item: T): any {
return this._mapFunc(item);
}
};