Project

General

Profile

1
import {UrlSegment} from '@angular/router';
2

    
3
export class Dates {
4
  public static yearMin = 1800;
5
  public static yearMax = (new Date().getFullYear()) + 10;
6
  public static currentYear = (new Date().getFullYear());
7

    
8
  public static isValidYear(yearString, yearMin=this.yearMin, yearMax=this.yearMax) {
9
    // First check for the pattern
10
    if (!/^\d{4}$/.test(yearString))
11
      return false;
12
    var year = parseInt(yearString, 10);
13
    
14
    // Check the ranges of month and year
15
    if (year < yearMin || year > yearMax)
16
      return false;
17
    return true;
18
  }
19
  
20
  //format YYYY-MM-DD
21
  public static isValidDate(dateString: string) {
22
    // First check for the pattern
23
    if (!/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(dateString))
24
      return false;
25
    
26
    // Parse the date parts to integers
27
    var parts = dateString.split("-");
28
    var day = parseInt(parts[2], 10);
29
    var month = parseInt(parts[1], 10);
30
    var year = parseInt(parts[0], 10);
31
    if (!this.isValidYear(parts[0])) {
32
      return false;
33
    }
34
    
35
    // Check the ranges of month and year
36
    if (month == 0 || month > 12)
37
      return false;
38
    
39
    var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
40
    
41
    // Adjust for leap years
42
    if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
43
      monthLength[1] = 29;
44
    
45
    // Check the range of the day
46
    return day > 0 && day <= monthLength[month - 1];
47
    
48
  }
49
  
50
  public static getDateToday(): Date {
51
    var myDate = new Date();
52
    return myDate;
53
    
54
  }
55
  
56
  public static getDateToString(myDate: Date): string {
57
    var date: string = myDate.getFullYear() + "-";
58
    date += ((myDate.getMonth() + 1) < 10) ? "0" + (myDate.getMonth() + 1) : (myDate.getMonth() + 1);
59
    date += "-";
60
    date += (myDate.getDate() < 10) ? "0" + myDate.getDate() : myDate.getDate();
61
    return date;
62
    
63
  }
64
  
65
  public static getDateXMonthsAgo(x: number): Date {
66
    var myDate = new Date();
67
    myDate.setMonth(myDate.getMonth() - x);
68
    return myDate;
69
    
70
  }
71
  
72
  public static getDateXYearsAgo(x: number): Date {
73
    var myDate = new Date();
74
    myDate.setFullYear(myDate.getFullYear() - x);
75
    return myDate;
76
    
77
  }
78
  
79
  public static getDateFromString(date: string): Date {
80
    
81
    var myDate = new Date();
82
    myDate.setFullYear(+date.substring(0, 4));
83
    myDate.setMonth(((date.length > 5) ? (+date.substring(5, 7) - 1) : (0)));
84
    myDate.setDate(((date.length > 8) ? (+date.substring(8, 11)) : (1)));
85
    return myDate;
86
    
87
  }
88
  
89
}
90

    
91
export class DOI {
92
  
93
  public static getDOIsFromString(str: string): string[] {
94
    return Identifier.getDOIsFromString(str);
95
  }
96
  
97
  public static isValidDOI(str: string): boolean {
98
    return Identifier.isValidDOI(str);
99
  }
100
}
101

    
102
export class Identifier {
103
  class: "doi" | "pmc" | "pmid" | "handle" | "ORCID" = null;
104
  id: string;
105
  
106
  public static getDOIsFromString(str: string): string[] {
107
    var DOIs: string[] = [];
108
    var words: string[] = str.split(" ");
109
    
110
    for (var i = 0; i < words.length; i++) {
111
      if (DOI.isValidDOI(words[i]) && DOIs.indexOf(words[i]) == -1) {
112
        DOIs.push(words[i]);
113
      }
114
    }
115
    return DOIs;
116
  }
117
  
118
  public static getIdentifiersFromString(str: string): Identifier[] {
119
    let identifiers: Identifier[] = [];
120
    let words: string[] = str.split(" ");
121
    
122
    for (let id of words) {
123
      if (id.length > 0) {
124
        if (Identifier.isValidDOI(id)) {
125
          identifiers.push({"class": "doi", "id": id})
126
        } else if (Identifier.isValidORCID(id)) {
127
          identifiers.push({"class": "ORCID", "id": id})
128
        } else if (Identifier.isValidPMCID(id)) {
129
          identifiers.push({"class": "pmc", "id": id})
130
        } else if (Identifier.isValidPMID(id)) {
131
          identifiers.push({"class": "pmid", "id": id})
132
        } else if (Identifier.isValidHANDLE(id)) {
133
          identifiers.push({"class": "handle", "id": id})
134
        }
135
      }
136
    }
137
    return identifiers;
138
  }
139
  
140
  public static isValidDOI(str: string): boolean {
141
    var exp1 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\b/g
142
    var exp2 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])[[:graph:]])+)\b/g
143
    return (str.match(exp1) != null || str.match(exp2) != null);
144
  }
145
  
146
  public static isValidORCID(str: string): boolean {
147
    let exp = /\b\d{4}-\d{4}-\d{4}-(\d{3}X|\d{4})\b/g;
148
    return str.match(exp) != null;
149
  }
150
  
151
  public static isValidPMID(str: string): boolean {
152
    let exp = /^\d*$/g;
153
    return str.match(exp) != null;
154
    
155
  }
156
  
157
  public static isValidPMCID(str: string): boolean {
158
    let exp = /^(PMC\d{7})$/g;
159
    return str.match(exp) != null;
160
  }
161
  
162
  public static isValidHANDLE(str: string): boolean {
163
    let exp = /^[0-9a-zA-Z-]*\/[0-9a-zA-Z-]*$/g;
164
    return str.match(exp) != null;
165
  }
166
}
167

    
168
export class StringUtils {
169
  public static urlPrefix(url: string): string {
170
    if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//")) {
171
      return "";
172
    } else {
173
      return "//";
174
    }
175
  }
176
  
177
  public static quote(params: string): string {
178
    return '"' + params + '"';
179
  }
180
  
181
  public static unquote(params: string): string {
182
    if (params.length > 2 && (params[0] == '"' && params[params.length - 1] == '"') || (params[0] == "'" && params[params.length - 1] == "'")) {
183
      params = params.substring(1, params.length - 1);
184
    }
185
    return params;
186
  }
187
  
188
  public static URIEncode(params: string): string {
189
    return encodeURIComponent(params);
190
  }
191
  
192
  public static URIDecode(params: string): string {
193
    return decodeURIComponent(params);
194
  }
195
  
196
  public static b64DecodeUnicode(str) {
197
    return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
198
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
199
    }).join(''));
200
  }
201
  
202
  private emailValidator(email: any): boolean {
203
    return !!email.match("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$");
204
  }
205
  
206
  public static sliceString(mystr, size: number): string {
207
    const sliced = String(mystr).substr(0, size);
208
    return sliced + (String(mystr).length > size ? '...' : '');
209
  }
210
  
211
  /**
212
   * Splits a text to words base on a list of separators. Returns the words of the text including the separators.
213
   * DO NOT TOUCH, IT WORKS
214
   *
215
   * @param text
216
   * @param separators
217
   */
218
  public static split(text: string, separators: string[]): string[] {
219
    let words: (string | string[])[] = [text];
220
    separators.forEach(separator => {
221
      words.forEach((word, index) => {
222
        if (typeof word === "string" && separators.indexOf(word) === -1) {
223
          let tokens: string[] = word.split(separator).filter(value => value !== '');
224
          if (tokens.length > 1) {
225
            words[index] = [];
226
            tokens.forEach((token, i) => {
227
              (<string[]>(words[index])).push(token);
228
              if (i !== (tokens.length - 1)) {
229
                (<string[]>(words[index])).push(separator);
230
              }
231
            });
232
          }
233
        }
234
      });
235
      words = [].concat.apply([], words);
236
    });
237
    return <string []>words;
238
  }
239
  
240
  public static capitalize(value: string): string {
241
    return value.charAt(0).toUpperCase() + value.slice(1);
242
  }
243
  
244
  /**
245
   * Checks if a text contains a word
246
   */
247
  public static containsWord(text: string, word: string):boolean {
248
    return (text && text.toLowerCase().includes(word));
249
  }
250
  
251
  public static URLSegmentsToPath(segments: UrlSegment[]): string {
252
    let path = '';
253
    segments.forEach(route => {
254
      path += '/' + route.path;
255
    })
256
    return path;
257
  }
258
  
259
  public static isEuropeanCountry(country: string) {
260
    let countries = ["Albania", "Andorra", "Armenia", "Austria", "Azerbaijan", "Belarus", "Belgium", "Bosnia and Herzegovina",
261
      "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Georgia", "Germany", "Greece", "Hungary", "Iceland", "Ireland",
262
      "Italy", "Kosovo", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Malta", "Moldova", "Monaco", "Montenegro", "The Netherlands", "Norway", "Poland",
263
      "Portugal", "Romania", "Russia", "San Marino", "Serbia", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "Ukraine", "United Kingdom", "Vatican City",
264
    ];
265
    return (country && countries.indexOf(country) != -1);
266
  }
267
  public static isOpenAIREID(id:string){
268
    if(id && id.length == 46){
269
      let exp1 = /^.{12}::([0-9a-z]{32})$/g;
270
      return (id.match(exp1)!=null);
271
    }
272
    return false;
273
  }
274
}
(21-21/21)