Completed
Push — master ( c17b81...3a1758 )
by Dimas
19:57 queued 11s
created

libs/js/app.ts   B

Complexity

Total Complexity 50
Complexity/F 8.33

Size

Lines of Code 471
Function Count 6

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 310
dl 0
loc 471
rs 8.4
c 0
b 0
f 0
wmc 50
mnd 44
bc 44
fnc 6
bpm 7.3333
cpm 8.3333
noi 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A app.load 0 17 4
F app.ts ➔ framework 0 6 31
C app.ts ➔ count 0 11 11
A app.direct 0 8 1
A app.setbase 0 2 1

How to fix   Complexity   

Complexity

Complex classes like libs/js/app.ts often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
function typedKeys<T>(o: T): (keyof T)[] {
2
  // type cast should be safe because that's what really Object.keys() does
3
  return Object.keys(o) as (keyof T)[];
4
}
5
var ORIGIN = null as any;
6
if (isnode()) {
7
  const process = require("process");
8
  ORIGIN = process.cwd();
9
} else {
10
  ORIGIN = location.protocol + "//" + location.host + location.pathname;
11
}
12
13
var dimas = {
14
  /**
15
   * get current url without querystrings
16
   */
17
  url: ORIGIN,
18
  /**
19
   * framework captcha
20
   */
21
  captcha: {
22
    /**
23
     * DO NOT ASSIGN THIS
24
     */
25
    check: null as NodeJS.Timer,
26
    /**
27
     * Get current captcha id
28
     */
29
    id: function (header_name: string | null): string {
30
      if (!dimas.captcha.check) {
31
        dimas.captcha.get(header_name);
32
      }
33
      return storage().get("captcha");
34
    },
35
    /**
36
     * Get current captcha from backend
37
     * And process it by jsonpCallback
38
     */
39
    get: function (header_name: null | string): void {
40
      if (!dimas.captcha.check) {
41
        dimas.captcha.check = setTimeout(() => {
42
          dimas.captcha.get(header_name);
43
        }, 60000);
44
      }
45
      var ua = md5(navigator.userAgent).rot13();
46
      var IP = ip.get(null);
47
      $.ajax({
48
        url: dimas.url + "?login=" + guid(),
49
        method: "POST",
50
        headers: {
51
          Accept: "application/javascript",
52
          [header_name]: ua,
53
          [IP.rot13()]: ua,
54
        },
55
        dataType: "jsonp",
56
        jsonpCallback: "framework().captcha.jspCallback",
57
      });
58
    },
59
60
    callback: function (arg?: any) {},
61
62
    /**
63
     * Captcha JSONP callback
64
     */
65
    jspCallback: function (res: { captcha: string }) {
66
      if (res.hasOwnProperty("captcha")) {
67
        storage().set("captcha", res.captcha.rot13());
68
        dimas.captcha.callback(storage().get("captcha"));
69
        dimas.captcha.listen();
70
      }
71
    },
72
    listener_started: null as any | string,
73
    /**
74
     * Form Captcha listener
75
     */
76
    listen: function () {
77
      if (dimas.captcha.listener_started) {
78
        return null;
79
      }
80
      dimas.captcha.listener_started = new Date().toISOString();
81
      return $(document).on("focus", "form[captcha]", function (e) {
82
        var captcha = $(this).find('[name="captcha"]');
83
        if (!captcha.length) {
84
          $(this).append(
85
            '<input type="hidden" name="captcha" id="' + guid() + '" />'
86
          );
87
          captcha = $(this).find('[name="captcha"]');
88
        }
89
        if (captcha.length) {
90
          captcha.val(storage().get("captcha").rot13());
91
        }
92
        var form = captcha.parents("form");
93
        var button = form.find('[type="submit"]');
94
        form.one("submit", function (e) {
95
          e.preventDefault();
96
          console.log("submit with captcha");
97
          button.prop("disabled", true);
98
          framework().captcha.callback = function () {
99
            button.prop("disabled", false);
100
          };
101
          framework().captcha.get(null);
102
          form.off("submit");
103
        });
104
        //captcha.parents('form').find('[type="submit"]').one('click', function());
105
      });
106
    },
107
  },
108
  /**
109
   * Count Array/Object/String length
110
   * @param {any[]|string|object} data
111
   */
112
  count(data: any[] | string | object) {
113
    if (Array.isArray(data) || typeof data == "string") {
114
      return data.length;
115
    } else if (typeof data == "object") {
116
      return Object.keys(data).length;
117
    } else if (typeof data == "number") {
118
      return data;
119
    }
120
  },
121
122
  /**
123
   * Make async function
124
   * @param callback
125
   */
126
  async: function (callback: any) {
127
    return new Promise(function (resolve, reject) {
128
      if (typeof callback == "function") {
129
        callback();
130
      }
131
      resolve();
132
    });
133
  },
134
  /**
135
   * Rupiah currency auto format
136
   */
137
  rp: function (angka: number, prefix: string | any) {
138
    if (!prefix) {
139
      prefix = "Rp. ";
140
    }
141
    var number_string = angka.toString().replace(/[^,\d]/g, ""),
142
      split = number_string.split(","),
143
      sisa = split[0].length % 3,
144
      rupiah = split[0].substr(0, sisa),
145
      ribuan = split[0].substr(sisa).match(/\d{3}/gi);
146
    if (ribuan) {
147
      var separator = sisa ? "." : "";
148
149
      rupiah += separator + ribuan.join(".");
150
    }
151
152
    rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
153
    return !prefix ? rupiah : prefix + " " + rupiah;
154
  },
155
  /**
156
   * Check if variable is number / numeric
157
   * @param {String|Number} v
158
   */
159
  isNumber: function (v: string | number) {
160
    return (
161
      !isNaN(parseInt(v.toString()) - parseFloat(v.toString())) &&
162
      /^\d+$/.test(v.toString())
163
    );
164
  },
165
  /**
166
   * strpad / startwith zero [0]
167
   * @param {number} val
168
   */
169
  strpad: function (val: number) {
170
    if (val >= 10) {
171
      return val;
172
    } else {
173
      return "0" + val;
174
    }
175
  },
176
  /**
177
   * Autofill datetime-local value
178
   */
179
  datetimelocal: function (v?: string | number) {
180
    var d = !v ? new Date() : new Date(v);
181
    $("input[type=datetime-local]").val(
182
      d.getFullYear() +
183
        "-" +
184
        this.strpad(d.getMonth() + 1) +
185
        "-" +
186
        this.strpad(d.getDate()) +
187
        "T" +
188
        this.strpad(d.getHours()) +
189
        ":" +
190
        this.strpad(d.getMinutes())
191
    );
192
  },
193
  /**
194
   * Get cookie
195
   * @param string name cookie
196
   */
197
  gc: function (name: string) {
198
    var nameEQ = name + "=";
199
    var ca = document.cookie.split(";");
200
    for (var i = 0; i < ca.length; i++) {
201
      var c = ca[i];
202
      while (c.charAt(0) == " ") {
203
        c = c.substring(1, c.length);
204
        if (c.indexOf(nameEQ) == 0) {
205
          return c.substring(nameEQ.length, c.length);
206
        }
207
      }
208
    }
209
210
    return null;
211
  },
212
213
  /**
214
   * Odd or Even (Ganjil Genap);
215
   * @param type odd or even
216
   */
217
  oddoreven: function (n: string, type: string) {
218
    if (!type) {
219
      type = "odd";
220
    }
221
    var time = !n ? new Date().getDay() : Number(n);
222
223
    if (!/^-{0,1}\d+jQuery/.test(time.toString())) {
224
      alert("arguments is not number, please remove quote");
225
      return null;
226
    }
227
228
    var hasil = time % 2;
229
230
    var type = /^(odd|ganjil)$/.test(type) ? "1" : "0";
231
    //return hasil == (type == ('odd' || 'ganjil') ? 1 : 0);
232
233
    return hasil.toString() == type.toString();
234
  },
235
236
  /**
237
   * Set cookie
238
   * @param {String} name
239
   * @param {any} value
240
   * @param {number} hours
241
   */
242
  sc: function (name: string, value: any, hours: number) {
243
    var expires = "";
244
    if (hours) {
245
      var date = new Date();
246
      date.setTime(date.getTime() + hours * 3600 * 1000);
247
      expires = "; expires=" + date.toUTCString();
248
    }
249
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
250
  },
251
252
  allcookies: function () {
253
    var pairs = document.cookie.split(";");
254
    var cookies: { [key: string]: any } = {};
255
    for (var i = 0; i < pairs.length; i++) {
256
      var pair = pairs[i].split("=");
257
      var str: string = pair[0].trim();
258
      cookies[str] = unescape(pair.slice(1).join("="));
259
    }
260
    return cookies;
261
  },
262
263
  /**
264
   * Remove Cookie
265
   */
266
  rc: function (name: string): void {
267
    document.cookie = name + "=; Max-Age=-99999999;";
268
  },
269
270
  /**
271
   * Get Query name from current url
272
   */
273
  getquery: function (variable: any) {
274
    var query = window.location.search.substring(1);
275
    var vars = query.split("&");
276
    for (var i = 0; i < vars.length; i++) {
277
      var pair = vars[i].split("=");
278
      if (pair[0] == variable) {
279
        return pair[1];
280
      }
281
    }
282
    return false;
283
  },
284
  recode: function (content: string, passcode: string) {
285
    var result = [];
286
    var str = "";
287
    var codesArr = JSON.parse(content);
288
    var passLen = passcode.length;
289
    for (var i = 0; i < codesArr.length; i++) {
290
      var passOffset = i % passLen;
291
      var calAscii = codesArr[i] - passcode.charCodeAt(passOffset);
292
      result.push(calAscii);
293
    }
294
    for (var i = 0; i < result.length; i++) {
295
      var ch = String.fromCharCode(result[i]);
296
      str += ch;
297
    }
298
    return str;
299
  },
300
  /**
301
   * Get js file from url
302
   * @param {String} url
303
   * @param {Function} callback
304
   */
305
  js: function (url: string, callback: Function | any) {
306
    var pel = document.body || document.head;
307
    var script = document.createElement("script");
308
    script.type = "text/javascript";
309
    script.src = url;
310
    if (typeof callback == "function") script.onreadystatechange = callback;
311
312
    script.onload = callback;
313
    pel.appendChild(script);
314
  },
315
  /**
316
   * Countdown trigger
317
   * @param {JQuery} elm
318
   */
319
  pctdRUN: function (elm: JQuery) {
320
    var tl = parseInt(elm.attr("countdown")) > 0 ? elm.attr("countdown") : 5,
321
      bs = elm.data("base") ? elm.data("base") : "bg-info",
322
      bw = elm.data("warning") ? elm.data("warning") : "bg-danger",
323
      bc = elm.data("success") ? elm.data("success") : "bg-success",
324
      countdown = elm.progressBarTimer({
325
        warningThreshold: 5,
326
        timeLimit: tl,
327
328
        // base style
329
        baseStyle: bs,
330
331
        // warning style
332
        warningStyle: bw,
333
334
        // complete style
335
        completeStyle: bc,
336
337
        // should the timer be smooth or stepping
338
        smooth: true,
339
340
        // striped progress bar
341
        striped: true,
342
343
        // animated stripes
344
        animated: true,
345
346
        // height of progress bar
347
        // 0 = default height
348
        height: 0,
349
        onFinish: function () {
350
          var callback = elm.data("callback");
351
          if (callback) {
352
            var xn = window[callback];
353
            if (typeof xn == "function") {
354
              var x = eval(callback);
355
              x();
356
            } else {
357
              console.log(callback + " isn't function ");
358
            }
359
          }
360
        },
361
        label: {
362
          show: true,
363
          type: "percent", // or 'seconds' => 23/60
364
        },
365
        autoStart: true,
366
      });
367
    return countdown;
368
  },
369
  /**
370
   * Progress Countdown
371
   * @param {JQuery} elm
372
   */
373
  pctd: function (elm: JQuery) {
374
    var t = this;
375
376
    if (typeof progressBarTimer == "undefined") {
377
      this.js(
378
        "https://cdn.jsdelivr.net/gh/dimaslanjaka/Web-Manajemen@master/js/jquery.progressBarTimer.js",
379
        function () {
380
          t.pctdRUN(elm);
381
        }
382
      );
383
    } else {
384
      window.onload = function (params: any) {
385
        dimas.pctdRUN(elm);
386
      };
387
    }
388
  },
389
390
  /**
391
   * Parseurl just like as parse_url at php
392
   */
393
  parseurl: function (url: string) {
394
    var parser = document.createElement("a"),
395
      searchObject: { [key: string]: any } = {},
396
      queries: string[],
397
      split: any[],
398
      i: number;
399
    // Let the browser do the work
400
    parser.href = url;
401
    // Convert query string to object
402
    queries = parser.search.replace(/^\?/, "").split("&");
403
    for (i = 0; i < queries.length; i++) {
404
      split = queries[i].split("=");
405
      searchObject[split[0]] = split[1];
406
    }
407
    return {
408
      protocol: parser.protocol,
409
      host: parser.host,
410
      hostname: parser.hostname,
411
      port: parser.port,
412
      pathname: parser.pathname,
413
      search: parser.search,
414
      searchObject: searchObject,
415
      hash: parser.hash,
416
      protohost: parser.protocol + "//" + parser.host,
417
    };
418
  },
419
};
420
421
/**
422
 * Framework object initializer
423
 */
424
function framework() {
425
  return dimas;
426
}
427
428
class app {
429
  static base = "/src/MVC/themes/assets/js/";
430
  static setbase(path: string) {
431
    this.base = path;
432
  }
433
  static direct(...args: string[]) {
434
    var scripts = document.querySelectorAll("script[src]");
435
    var last = scripts[scripts.length - 1];
436
    var lastsrc = last.getAttribute("src");
437
    var parsed = dimas.parseurl(lastsrc);
438
    args.forEach(function (src) {
439
      dimas.js(`${app.base}${src}${parsed.search}`, function () {
440
        console.log(`${src} engine inbound`);
441
      });
442
    });
443
  }
444
  static load(...args: any[]) {
445
    var scripts = document.querySelectorAll("script[src]");
446
    var last = scripts[scripts.length - 1];
447
    var lastsrc = last.getAttribute("src");
448
    var parsed = dimas.parseurl(lastsrc);
449
    args.forEach(function (key, index) {
450
      console.log(key, app.base);
451
      let src: string = "";
452
      if (/^(ajx|ajaxjQuery|ajxjquery|ajquery)$/s.test(key)) {
453
        src = "ajaxJquery.js";
454
      } else if (/^(ajv|ajaxVanilla|ajaxv|avanilla)$/s.test(key)) {
455
        src = "ajaxVanilla.js";
456
      }
457
458
      if (src != "") {
459
        dimas.js(`${app.base}${src}${parsed.search}`, function () {
460
          console.log(`${src} engine inbound`);
461
        });
462
      }
463
    });
464
  }
465
}
466
467
if (typeof module !== "undefined" && module.exports) {
468
  module.exports.app = app;
469
  module.exports.dimas = dimas;
470
}
471
472
//app.direct('Array.js', 'Object.js', 'saver.js', 'user.js');
473