1 |
|
2 |
|
3 |
|
4 |
|
5 | import * as ts from 'typescript';
|
6 | export namespace Utils {
|
7 | |
8 |
|
9 |
|
10 | export function exists<T extends ts.Node>(list: ts.NodeArray<T>, predicate: (t: T) => boolean): boolean {
|
11 | if (list != null) {
|
12 | for (let i = 0; i < list.length; i++) {
|
13 | const obj: T = list[i];
|
14 | if (predicate(obj)) {
|
15 | return true;
|
16 | }
|
17 | }
|
18 | }
|
19 | return false;
|
20 | }
|
21 |
|
22 | |
23 |
|
24 |
|
25 | export function contains<T extends ts.Node>(list: ts.NodeArray<T>, element: T): boolean {
|
26 | return exists(
|
27 | list,
|
28 | (item: T): boolean => {
|
29 | return item === element;
|
30 | }
|
31 | );
|
32 | }
|
33 |
|
34 | |
35 |
|
36 |
|
37 | export function removeAll<T extends ts.Node>(source: ts.NodeArray<T>, elementsToRemove: ts.NodeArray<T>): T[] {
|
38 | if (source == null || source.length === 0) {
|
39 | return [];
|
40 | }
|
41 | if (elementsToRemove == null || elementsToRemove.length === 0) {
|
42 | return [].concat(source);
|
43 | }
|
44 |
|
45 | return source.filter(
|
46 | (sourceElement: T): boolean => {
|
47 | return !contains(elementsToRemove, sourceElement);
|
48 | }
|
49 | );
|
50 | }
|
51 |
|
52 | |
53 |
|
54 |
|
55 | export function remove<T extends ts.Node>(source: ts.NodeArray<T>, elementToRemove: T): T[] {
|
56 | return removeAll(source, <any>[elementToRemove]);
|
57 | }
|
58 |
|
59 | export function trimTo(source: string, maxLength: number): string {
|
60 | if (source == null) {
|
61 | return '';
|
62 | }
|
63 | if (source.length <= maxLength) {
|
64 | return source;
|
65 | }
|
66 | return source.substr(0, maxLength - 2) + '...';
|
67 | }
|
68 |
|
69 | |
70 |
|
71 |
|
72 | export function arraysShallowEqual(arr1: any[], arr2: any[]) {
|
73 | if (arr1.length !== arr2.length) {
|
74 | return false;
|
75 | }
|
76 | for (let i = arr1.length; i--; ) {
|
77 | if (arr1[i] !== arr2[i]) {
|
78 | return false;
|
79 | }
|
80 | }
|
81 | return true;
|
82 | }
|
83 | }
|
84 |
|