Project

General

Profile

1 61381 k.triantaf
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,strict:boolean = true): 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
    //set it as a doi, to catch the case that doi has not valid format
193
    return (strict?null:{"class": "doi", "id": pid});
194
  }
195
196
  public static getResultPIDFromIdentifiers(identifiers: Map<string, string[]>): Identifier {
197
    let classes:string [] = ["doi", "handle", "pmc", "pmid"];
198
      if(identifiers) {
199
        for (let cl of classes){
200
          if(identifiers.get(cl)){
201
            for (let pid of  identifiers.get(cl)) {
202
              let identifier =  Identifier.getIdentifierFromString(pid);
203
              if (identifier){
204
                return identifier;
205
              }
206
            }
207
          }
208
      }
209
      return null;
210
    }
211
  }
212
213
  public static isValidDOI(str: string): boolean {
214
    //keep only exp3?
215
    let exp1 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\b/g;
216
    let exp2 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])[[:graph:]])+)\b/g;
217
    let exp3 = /\b(10[.]*)\b/g;
218
    return (str.match(exp1) != null || str.match(exp2) != null || str.match(exp3) != null);
219
  }
220
221
  public static isValidORCID(str: string): boolean {
222
    let exp = /\b\d{4}-\d{4}-\d{4}-(\d{3}X|\d{4})\b/g;
223
    return str.match(exp) != null;
224
  }
225
226
  public static isValidPMID(str: string): boolean {
227
    let exp = /^\d*$/g;
228
    return str.match(exp) != null;
229
230
  }
231
232
  public static isValidPMCID(str: string): boolean {
233
    let exp = /^(PMC\d{7})$/g;
234
    return str.match(exp) != null;
235
  }
236
237
  public static isValidHANDLE(str: string): boolean {
238
    let exp = /^[0-9a-zA-Z-]*\/[0-9a-zA-Z-]*$/g;
239
    return str.match(exp) != null;
240
  }
241
}
242
243
export class StringUtils {
244
245
  public static urlRegex = 'https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.' +
246
    '[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.' +
247
    '[a-zA-Z0-9]+\.[^\s]{2,}';
248
249
  public static urlPrefix(url: string): string {
250
    if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//")) {
251
      return "";
252
    } else {
253
      return "//";
254
    }
255
  }
256
257
  public static quote(params: string): string {
258
    return '"' + params + '"';
259
  }
260
261
  public static unquote(params: string): string {
262
    if (params.length > 2 && (params[0] == '"' && params[params.length - 1] == '"') || (params[0] == "'" && params[params.length - 1] == "'")) {
263
      params = params.substring(1, params.length - 1);
264
    }
265
    return params;
266
  }
267
268
  public static URIEncode(params: string): string {
269
    return encodeURIComponent(params);
270
  }
271
272
  public static URIDecode(params: string): string {
273
    return decodeURIComponent(params);
274
  }
275
276
  public static validateEmails(emails: string): boolean {
277
    return (emails.split(',')
278
      .map(email => Validators.email(<AbstractControl>{value: email.trim()}))
279
      .find(_ => _ !== null) === undefined);
280
  }
281
282
  public static b64DecodeUnicode(str) {
283
    return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
284
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
285
    }).join(''));
286
  }
287
288
  private emailValidator(email: any): boolean {
289
    return !!email.match("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$");
290
  }
291
292
  public static isValidUrl(url: string): boolean {
293
    return new RegExp(this.urlRegex).test(url);
294
  }
295
296
  public static urlValidator(): ValidatorFn {
297
    return Validators.pattern(StringUtils.urlRegex);
298
  }
299
300
  public static sliceString(mystr, size: number): string {
301
    const sliced = String(mystr).substr(0, size);
302
    return sliced + (String(mystr).length > size ? '...' : '');
303
  }
304
305
  /**
306
   * Splits a text to words base on a list of separators. Returns the words of the text including the separators.
307
   * DO NOT TOUCH, IT WORKS
308
   *
309
   * @param text
310
   * @param separators
311
   */
312
  public static split(text: string, separators: string[]): string[] {
313
    let words: (string | string[])[] = [text];
314
    separators.forEach(separator => {
315
      words.forEach((word, index) => {
316
        if (typeof word === "string" && separators.indexOf(word) === -1) {
317
          let tokens: string[] = word.split(separator).filter(value => value !== '');
318
          if (tokens.length > 1) {
319
            words[index] = [];
320
            tokens.forEach((token, i) => {
321
              (<string[]>(words[index])).push(token);
322
              if (i !== (tokens.length - 1)) {
323
                (<string[]>(words[index])).push(separator);
324
              }
325
            });
326
          }
327
        }
328
      });
329
      words = [].concat.apply([], words);
330
    });
331
    return <string []>words;
332
  }
333
334
  public static capitalize(value: string): string {
335
    return value.charAt(0).toUpperCase() + value.slice(1);
336
  }
337
338
  /**
339
   * Checks if a text contains a word
340
   */
341
  public static containsWord(text: string, word: string): boolean {
342
    return (text && text.toLowerCase().includes(word));
343
  }
344
345
  public static URLSegmentsToPath(segments: UrlSegment[]): string {
346
    let path = '';
347
    segments.forEach(route => {
348
      path += '/' + route.path;
349
    })
350
    return path;
351
  }
352
353
  public static isEuropeanCountry(country: string) {
354
    let countries = ["Albania", "Andorra", "Armenia", "Austria", "Azerbaijan", "Belarus", "Belgium", "Bosnia and Herzegovina",
355
      "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Georgia", "Germany", "Greece", "Hungary", "Iceland", "Ireland",
356
      "Italy", "Kosovo", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Malta", "Moldova", "Monaco", "Montenegro", "The Netherlands", "Norway", "Poland",
357
      "Portugal", "Romania", "Russia", "San Marino", "Serbia", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "Ukraine", "United Kingdom", "Vatican City",
358
    ];
359
    return (country && countries.indexOf(country) != -1);
360
  }
361
362
  public static isOpenAIREID(id: string) {
363
    if (id && id.length == 46) {
364
      let exp1 = /^.{12}::([0-9a-z]{32})$/g;
365
      return (id.match(exp1) != null);
366
    }
367
    return false;
368
  }
369
  public static HTMLToString( html:string){
370
     try {
371
       html = html.replace(/&nbsp;/g, ' ');
372
       html = html.replace(/(\r\n|\n|\r| +(?= ))|\s\s+/gm, " ");
373
       html = html.replace(/<[^>]*>/g, '');
374
    }catch( e){
375
    }
376
   return html;
377
  }
378
}