Project

General

Profile

1
import {UrlSegment} from '@angular/router';
2
import {AbstractControl, ValidatorFn, Validators} from "@angular/forms";
3

    
4
export class Dates {
5
  public static yearMin = 1800;
6
  public static yearMax = (new Date().getFullYear()) + 10;
7
  public static currentYear = (new Date().getFullYear());
8
  
9
  public static isValidYear(yearString, yearMin = this.yearMin, yearMax = this.yearMax) {
10
    // First check for the pattern
11
    if (!/^\d{4}$/.test(yearString))
12
      return false;
13
    var year = parseInt(yearString, 10);
14
    
15
    // Check the ranges of month and year
16
    if (year < yearMin || year > yearMax)
17
      return false;
18
    return true;
19
  }
20
  
21
  //format YYYY-MM-DD
22
  public static isValidDate(dateString: string) {
23
    // First check for the pattern
24
    if (!/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(dateString))
25
      return false;
26
    
27
    // Parse the date parts to integers
28
    var parts = dateString.split("-");
29
    var day = parseInt(parts[2], 10);
30
    var month = parseInt(parts[1], 10);
31
    var year = parseInt(parts[0], 10);
32
    if (!this.isValidYear(parts[0])) {
33
      return false;
34
    }
35
    
36
    // Check the ranges of month and year
37
    if (month == 0 || month > 12)
38
      return false;
39
    
40
    var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
41
    
42
    // Adjust for leap years
43
    if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
44
      monthLength[1] = 29;
45
    
46
    // Check the range of the day
47
    return day > 0 && day <= monthLength[month - 1];
48
    
49
  }
50
  
51
  public static getDateToday(): Date {
52
    var myDate = new Date();
53
    return myDate;
54
    
55
  }
56
  
57
  public static getDateToString(myDate: Date): string {
58
    var date: string = myDate.getFullYear() + "-";
59
    date += ((myDate.getMonth() + 1) < 10) ? "0" + (myDate.getMonth() + 1) : (myDate.getMonth() + 1);
60
    date += "-";
61
    date += (myDate.getDate() < 10) ? "0" + myDate.getDate() : myDate.getDate();
62
    return date;
63
    
64
  }
65
  
66
  public static getDateXMonthsAgo(x: number): Date {
67
    var myDate = new Date();
68
    myDate.setMonth(myDate.getMonth() - x);
69
    return myDate;
70
    
71
  }
72
  
73
  public static getDateXYearsAgo(x: number): Date {
74
    var myDate = new Date();
75
    myDate.setFullYear(myDate.getFullYear() - x);
76
    return myDate;
77
    
78
  }
79
  
80
  public static getDateFromString(date: string): Date {
81
    
82
    var myDate = new Date();
83
    myDate.setFullYear(+date.substring(0, 4));
84
    myDate.setMonth(((date.length > 5) ? (+date.substring(5, 7) - 1) : (0)));
85
    myDate.setDate(((date.length > 8) ? (+date.substring(8, 11)) : (1)));
86
    return myDate;
87
    
88
  }
89
  
90
  public static getDate(dateString: string): Date {
91
    let date = new Date(dateString);
92
    if (Object.prototype.toString.call(date) === "[object Date]") {
93
      if (isNaN(date.getTime())) {
94
        return null;
95
      } else {
96
        return date;
97
      }
98
    } else {
99
      return null;
100
    }
101
  }
102
  
103
  public static timeSince(date: Date) {
104
    
105
    let seconds = Math.floor((new Date().getTime() - new Date(date).getTime()) / 1000);
106
    
107
    let interval = seconds / (365*24*60*60);
108
    
109
    if (interval > 1) {
110
      let years = Math.floor(interval);
111
      return  (years > 1?(years + ' years ago'):'a year ago');
112
    }
113
    interval = seconds / (7*24*60*60);
114
    if (interval > 1) {
115
      let weeks = Math.floor(interval);
116
      return  (weeks > 1?(weeks + ' weeks ago'):'a week ago');
117
    }
118
    interval = seconds / (24*60*60);
119
    if (interval > 1) {
120
      let days = Math.floor(interval);
121
      return  (days > 1?(days + ' days ago'):'a day ago');
122
    }
123
    interval = seconds / (60*60);
124
    if (interval > 1) {
125
      let hours = Math.floor(interval);
126
      return  (hours > 1?(hours + ' hours ago'):'an hour ago');
127
    }
128
    interval = seconds / 60;
129
    if (interval > 1) {
130
      let minutes = Math.floor(interval);
131
      return  (minutes > 1?(minutes + ' minutes ago'):'a minute ago');
132
    }
133
    seconds = Math.floor(interval);
134
    return  (seconds > 1?(seconds + ' seconds ago'):' just now');
135
  }
136
}
137

    
138
export class DOI {
139
  
140
  public static getDOIsFromString(str: string): string[] {
141
    return Identifier.getDOIsFromString(str);
142
  }
143
  
144
  public static isValidDOI(str: string): boolean {
145
    return Identifier.isValidDOI(str);
146
  }
147
}
148

    
149
export class Identifier {
150
  class: "doi" | "pmc" | "pmid" | "handle" | "ORCID" = null;
151
  id: string;
152
  
153
  public static getDOIsFromString(str: string): string[] {
154
    var DOIs: string[] = [];
155
    var words: string[] = str.split(" ");
156
    
157
    for (var i = 0; i < words.length; i++) {
158
      if (DOI.isValidDOI(words[i]) && DOIs.indexOf(words[i]) == -1) {
159
        DOIs.push(words[i]);
160
      }
161
    }
162
    return DOIs;
163
  }
164
  
165
  public static getIdentifiersFromString(str: string): Identifier[] {
166
    let identifiers: Identifier[] = [];
167
    let words: string[] = str.split(" ");
168
    
169
    for (let id of words) {
170
      if (id.length > 0) {
171
        let identifier: Identifier = this.getIdentifierFromString(id);
172
        if (identifier) {
173
          identifiers.push(identifier);
174
        }
175
      }
176
    }
177
    return identifiers;
178
  }
179
  
180
  public static getIdentifierFromString(pid: string): Identifier {
181
    if (Identifier.isValidDOI(pid)) {
182
      return {"class": "doi", "id": pid};
183
    } else if (Identifier.isValidORCID(pid)) {
184
      return {"class": "ORCID", "id": pid};
185
    } else if (Identifier.isValidPMCID(pid)) {
186
      return {"class": "pmc", "id": pid};
187
    } else if (Identifier.isValidPMID(pid)) {
188
      return {"class": "pmid", "id": pid};
189
    } else if (Identifier.isValidHANDLE(pid)) {
190
      return {"class": "handle", "id": pid};
191
    }
192
    return null;
193
  }
194

    
195
  public static getResultPIDFromIdentifiers(identifiers: Map<string, string[]>): Identifier {
196
    let classes:string [] = ["doi", "handle", "pmc", "pmid"];
197
      if(identifiers) {
198
        for (let cl of classes){
199
          if(identifiers.get(cl)){
200
            for (let pid of  identifiers.get(cl)) {
201
              let identifier =  Identifier.getIdentifierFromString(pid);
202
              if (identifier){
203
                return identifier;
204
              }
205
            }
206
          }
207
      }
208
      return null;
209
    }
210
  }
211
  
212
  public static isValidDOI(str: string): boolean {
213
    var exp1 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\b/g
214
    var exp2 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])[[:graph:]])+)\b/g
215
    return (str.match(exp1) != null || str.match(exp2) != null);
216
  }
217
  
218
  public static isValidORCID(str: string): boolean {
219
    let exp = /\b\d{4}-\d{4}-\d{4}-(\d{3}X|\d{4})\b/g;
220
    return str.match(exp) != null;
221
  }
222
  
223
  public static isValidPMID(str: string): boolean {
224
    let exp = /^\d*$/g;
225
    return str.match(exp) != null;
226
    
227
  }
228
  
229
  public static isValidPMCID(str: string): boolean {
230
    let exp = /^(PMC\d{7})$/g;
231
    return str.match(exp) != null;
232
  }
233
  
234
  public static isValidHANDLE(str: string): boolean {
235
    let exp = /^[0-9a-zA-Z-]*\/[0-9a-zA-Z-]*$/g;
236
    return str.match(exp) != null;
237
  }
238
}
239

    
240
export class StringUtils {
241
  
242
  public static urlRegex = 'https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.' +
243
    '[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.' +
244
    '[a-zA-Z0-9]+\.[^\s]{2,}';
245
  
246
  public static urlPrefix(url: string): string {
247
    if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//")) {
248
      return "";
249
    } else {
250
      return "//";
251
    }
252
  }
253
  
254
  public static quote(params: string): string {
255
    return '"' + params + '"';
256
  }
257
  
258
  public static unquote(params: string): string {
259
    if (params.length > 2 && (params[0] == '"' && params[params.length - 1] == '"') || (params[0] == "'" && params[params.length - 1] == "'")) {
260
      params = params.substring(1, params.length - 1);
261
    }
262
    return params;
263
  }
264
  
265
  public static URIEncode(params: string): string {
266
    return encodeURIComponent(params);
267
  }
268
  
269
  public static URIDecode(params: string): string {
270
    return decodeURIComponent(params);
271
  }
272
  
273
  public static validateEmails(emails: string): boolean {
274
    return (emails.split(',')
275
      .map(email => Validators.email(<AbstractControl>{value: email.trim()}))
276
      .find(_ => _ !== null) === undefined);
277
  }
278
  
279
  public static b64DecodeUnicode(str) {
280
    return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
281
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
282
    }).join(''));
283
  }
284
  
285
  private emailValidator(email: any): boolean {
286
    return !!email.match("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$");
287
  }
288
  
289
  public static isValidUrl(url: string): boolean {
290
    return new RegExp(this.urlRegex).test(url);
291
  }
292
  
293
  public static urlValidator(): ValidatorFn {
294
    return Validators.pattern(StringUtils.urlRegex);
295
  }
296
  
297
  public static sliceString(mystr, size: number): string {
298
    const sliced = String(mystr).substr(0, size);
299
    return sliced + (String(mystr).length > size ? '...' : '');
300
  }
301
  
302
  /**
303
   * Splits a text to words base on a list of separators. Returns the words of the text including the separators.
304
   * DO NOT TOUCH, IT WORKS
305
   *
306
   * @param text
307
   * @param separators
308
   */
309
  public static split(text: string, separators: string[]): string[] {
310
    let words: (string | string[])[] = [text];
311
    separators.forEach(separator => {
312
      words.forEach((word, index) => {
313
        if (typeof word === "string" && separators.indexOf(word) === -1) {
314
          let tokens: string[] = word.split(separator).filter(value => value !== '');
315
          if (tokens.length > 1) {
316
            words[index] = [];
317
            tokens.forEach((token, i) => {
318
              (<string[]>(words[index])).push(token);
319
              if (i !== (tokens.length - 1)) {
320
                (<string[]>(words[index])).push(separator);
321
              }
322
            });
323
          }
324
        }
325
      });
326
      words = [].concat.apply([], words);
327
    });
328
    return <string []>words;
329
  }
330
  
331
  public static capitalize(value: string): string {
332
    return value.charAt(0).toUpperCase() + value.slice(1);
333
  }
334
  
335
  /**
336
   * Checks if a text contains a word
337
   */
338
  public static containsWord(text: string, word: string): boolean {
339
    return (text && text.toLowerCase().includes(word));
340
  }
341
  
342
  public static URLSegmentsToPath(segments: UrlSegment[]): string {
343
    let path = '';
344
    segments.forEach(route => {
345
      path += '/' + route.path;
346
    })
347
    return path;
348
  }
349
  
350
  public static isEuropeanCountry(country: string) {
351
    let countries = ["Albania", "Andorra", "Armenia", "Austria", "Azerbaijan", "Belarus", "Belgium", "Bosnia and Herzegovina",
352
      "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Georgia", "Germany", "Greece", "Hungary", "Iceland", "Ireland",
353
      "Italy", "Kosovo", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Malta", "Moldova", "Monaco", "Montenegro", "The Netherlands", "Norway", "Poland",
354
      "Portugal", "Romania", "Russia", "San Marino", "Serbia", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "Ukraine", "United Kingdom", "Vatican City",
355
    ];
356
    return (country && countries.indexOf(country) != -1);
357
  }
358
  
359
  public static isOpenAIREID(id: string) {
360
    if (id && id.length == 46) {
361
      let exp1 = /^.{12}::([0-9a-z]{32})$/g;
362
      return (id.match(exp1) != null);
363
    }
364
    return false;
365
  }
366
  public static HTMLToString( html:string){
367
     try {
368
       html = html.replace(/&nbsp;/g, ' ');
369
       html = html.replace(/(\r\n|\n|\r| +(?= ))|\s\s+/gm, " ");
370
       html = html.replace(/<[^>]*>/g, '');
371
    }catch( e){
372
    }
373
   return html;
374
  }
375
}
(22-22/22)