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){
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 < this.yearMin || year > this.yearMax )
16
            return false;
17
        return true;
18
  }
19
  //format YYYY-MM-DD
20
  public static isValidDate(dateString:string)
21
  {
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
  public static getDateToday():Date{
50
    var myDate = new Date();
51
    return myDate;
52

    
53
  }
54
  public static getDateToString(myDate:Date):string{
55
    var date:string = myDate.getFullYear()+ "-" ;
56
     date+=((myDate.getMonth() + 1)<10)?"0"+(myDate.getMonth() + 1):(myDate.getMonth() + 1) ;
57
     date+="-";
58
     date+=  (myDate.getDate() <10 )? "0"+myDate.getDate():myDate.getDate() ;
59
     return date;
60

    
61
  }
62
  public static getDateXMonthsAgo(x:number):Date{
63
    var myDate = new Date();
64
    myDate.setMonth(myDate.getMonth() - x);
65
    return myDate;
66

    
67
  }
68
  public static getDateXYearsAgo(x:number):Date{
69
    var myDate = new Date();
70
    myDate.setFullYear(myDate.getFullYear() - x);
71
    return myDate;
72

    
73
  }
74
  public static getDateFromString(date:string):Date{
75

    
76
    var myDate = new Date();
77
    myDate.setFullYear(+date.substring(0,4));
78
    myDate.setMonth(((date.length>5 )?(+date.substring(5,7)-1):(0)));
79
    myDate.setDate(((date.length>8 )?(+date.substring(8,11)):(1)));
80
    return myDate;
81

    
82
  }
83

    
84
}
85

    
86
export class DOI{
87

    
88
  public static getDOIsFromString(str:string):string[]{
89
    return Identifier.getDOIsFromString(str);
90
  }
91
  public static isValidDOI(str:string):boolean{
92
    return Identifier.isValidDOI(str);
93
  }
94
}
95

    
96
export class Identifier{
97
    class: "doi" | "pmc" | "pmid" | "handle"|"ORCID" =null;
98
    id:string;
99

    
100
  public static getDOIsFromString(str:string):string[]{
101
    var DOIs:string[] = [];
102
    var words:string[] = str.split(" ");
103

    
104
    for(var i=0; i< words.length; i++){
105
      if(DOI.isValidDOI(words[i]) && DOIs.indexOf(words[i]) == -1){
106
        DOIs.push(words[i]);
107
      }
108
    }
109
    return DOIs;
110
  }
111
  public static getIdentifiersFromString(str:string):Identifier[]{
112
    let identifiers:Identifier[] = [];
113
    let words:string[] = str.split(" ");
114

    
115
    for(let id of words){
116
      if(id.length > 0 ) {
117
        if (Identifier.isValidDOI(id)) {
118
          identifiers.push({"class": "doi", "id": id})
119
        } else if (Identifier.isValidORCID(id)) {
120
          identifiers.push({"class": "ORCID", "id": id})
121
        } else if (Identifier.isValidPMCID(id)) {
122
          identifiers.push({"class": "pmc", "id": id})
123
        } else if (Identifier.isValidPMID(id)) {
124
          identifiers.push({"class": "pmid", "id": id})
125
        } else if (Identifier.isValidHANDLE(id)) {
126
          identifiers.push({"class": "handle", "id": id})
127
        }
128
      }
129
    }
130
    return identifiers;
131
  }
132
  public static isValidDOI(str:string):boolean{
133
    var exp1 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\b/g
134
    var exp2 = /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])[[:graph:]])+)\b/g
135
    return (str.match(exp1)!=null || str.match(exp2)!=null);
136
  }
137
  public static isValidORCID(str:string):boolean{
138
    let exp =/\b\d{4}-\d{4}-\d{4}-(\d{3}X|\d{4})\b/g;
139
    return str.match(exp)!=null;
140
  }
141
  public static isValidPMID(str:string):boolean{
142
    let exp =/^\d*$/g;
143
    return str.match(exp)!=null;
144

    
145
  }
146
  public static isValidPMCID(str:string):boolean{
147
    let exp =/^(PMC\d{7})$/g;
148
    return str.match(exp)!=null;
149
  }
150

    
151
  public static isValidHANDLE(str:string):boolean{
152
    let exp =/^[0-9a-zA-Z-]*\/[0-9a-zA-Z-]*$/g;
153
    return str.match(exp)!=null;
154
  }
155
}
156
export class StringUtils{
157
  public static urlPrefix(url: string): string {
158
    if(url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//")) {
159
      return "";
160
    } else {
161
      return "//";
162
    }
163
  }
164

    
165
  public static quote(params: string):string {
166
      return '"'+params+'"';
167
  }
168

    
169
  public static unquote(params: string):string {
170
     if(params.length > 2 && (params[0]=='"' && params[params.length-1]=='"') || (params[0]=="'" && params[params.length-1]=="'")){
171
      params= params.substring(1, params.length-1);
172
    }
173
      return params;
174
  }
175
  public static URIEncode(params: string):string {
176
      return encodeURIComponent(params);
177
  }
178
  public static URIDecode(params: string):string {
179
      return decodeURIComponent(params);
180
  }
181
  public static  b64DecodeUnicode(str) {
182
      return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
183
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
184
      }).join(''));
185
  }
186
  private emailValidator(email : any): boolean {
187
      if (email.match("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"))
188
          return true;
189
      else
190
          return false;
191
  }
192
  public static sliceString(mystr, size: number): string {
193
    const sliced = String(mystr).substr(0, size);
194
    return sliced + (String(mystr).length > size ? '...' : '');
195
  }
196
  
197
  /**
198
   * Splits a text to words base on a list of separators. Returns the words of the text including the separators.
199
   * DO NOT TOUCH, IT WORKS
200
   *
201
   * @param text
202
   * @param separators
203
   */
204
  public static split(text: string, separators: string[]): string[] {
205
    let words: (string | string[])[] = [text];
206
    separators.forEach(separator => {
207
      words.forEach((word, index) => {
208
        if(typeof word === "string" && separators.indexOf(word) === -1) {
209
          let tokens: string[] = word.split(separator).filter(value => value !== '');
210
          if(tokens.length > 1) {
211
            words[index] = [];
212
            tokens.forEach((token, i) => {
213
              (<string[]>(words[index])).push(token);
214
              if(i !== (tokens.length - 1)) {
215
                (<string[]>(words[index])).push(separator);
216
              }
217
            });
218
          }
219
        }
220
      });
221
      words = [].concat.apply([], words);
222
    });
223
    return <string []>words;
224
  }
225
  
226
  public static capitalize(value: string): string {
227
    return value.charAt(0).toUpperCase() + value.slice(1);
228
  }
229

    
230
  public static URLSegmentsToPath(segments: UrlSegment[]): string {
231
    let path = '';
232
    segments.forEach(route => {
233
      path += '/' + route.path;
234
    })
235
    return path;
236
  }
237
  public static isEuropeanCountry(country:string){
238
    let countries =["Albania", "Andorra", "Armenia", "Austria", "Azerbaijan", "Belarus", "Belgium", "Bosnia and Herzegovina",
239
      "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Georgia", "Germany", "Greece", "Hungary", "Iceland", "Ireland",
240
      "Italy", "Kosovo", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Malta", "Moldova", "Monaco", "Montenegro", "The Netherlands", "Norway","Poland",
241
      "Portugal", "Romania", "Russia", "San Marino", "Serbia", "Slovakia","Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "Ukraine", "United Kingdom", "Vatican City",
242
    ];
243
    return (country && countries.indexOf(country)!= -1);
244

    
245
    }
246
}
(21-21/21)