-
Notifications
You must be signed in to change notification settings - Fork 24.7k
/
collection.ts
81 lines (71 loc) 路 2.24 KB
/
collection.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {傻isPromise as isPromise} from '@angular/core';
import {from, isObservable, Observable, of} from 'rxjs';
import {Data} from '../models';
export function shallowEqualArrays(a: any[], b: any[]): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; ++i) {
if (!shallowEqual(a[i], b[i])) return false;
}
return true;
}
export function shallowEqual(a: Data, b: Data): boolean {
// While `undefined` should never be possible, it would sometimes be the case in IE 11
// and pre-chromium Edge. The check below accounts for this edge case.
const k1 = a ? getDataKeys(a) : undefined;
const k2 = b ? getDataKeys(b) : undefined;
if (!k1 || !k2 || k1.length != k2.length) {
return false;
}
let key: string|symbol;
for (let i = 0; i < k1.length; i++) {
key = k1[i];
if (!equalArraysOrString(a[key], b[key])) {
return false;
}
}
return true;
}
/**
* Gets the keys of an object, including `symbol` keys.
*/
export function getDataKeys(obj: Object): Array<string|symbol> {
return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)];
}
/**
* Test equality for arrays of strings or a string.
*/
export function equalArraysOrString(a: string|string[], b: string|string[]) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return false;
const aSorted = [...a].sort();
const bSorted = [...b].sort();
return aSorted.every((val, index) => bSorted[index] === val);
} else {
return a === b;
}
}
/**
* Return the last element of an array.
*/
export function last<T>(a: T[]): T|null {
return a.length > 0 ? a[a.length - 1] : null;
}
export function wrapIntoObservable<T>(value: T|Promise<T>|Observable<T>): Observable<T> {
if (isObservable(value)) {
return value;
}
if (isPromise(value)) {
// Use `Promise.resolve()` to wrap promise-like instances.
// Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
// change detection.
return from(Promise.resolve(value));
}
return of(value);
}