summaryrefslogtreecommitdiffstats
path: root/src/wwwroot/scripts/prototypes.js
blob: 94960228e1a28992e5066131e9be76a7ac769b64 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"use strict";
Date.prototype.addDays = function (days) {
    let date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
};

Date.prototype.substractDays = function (days) {
    let date = new Date(this.valueOf());
    date.setDate(date.getDate() - days);
    return date;
};

Storage.prototype.removeRegex = function (r) {
    if (!r) return;
    let n = sessionStorage.length;
    while (n--) {
        let key = sessionStorage.key(n);
        let rx = new RegExp(r);
        if (rx.test(key)) {
            sessionStorage.removeItem(key);
        }
    }
};

Storage.prototype.setStringified = function (key, value) {
    let stringified = JSON.stringify(value);
    sessionStorage.setItem(key, stringified);
};

Storage.prototype.getParsedValue = function (key) {
    try {
        let value = sessionStorage.getItem(key);
        return JSON.parse(value);
    } catch (e) {
        return null;
    }
};

//"Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"});
String.prototype.formatUnicorn = function () {
    let str = this.toString();
    if (arguments.length) {
        let t = typeof arguments[0];
        let key;
        let args = ("string" === t || "number" === t) ?
            Array.prototype.slice.call(arguments)
            : arguments[0];
        for (key in args) {
            str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
        }
    }
    return str;
};

//"Hello, {0}, are you feeling {1}?".format("Gabriel", "OK");
String.prototype.format = function () {
    let args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined'
            ? args[number]
            : match
            ;
    });
};

String.prototype.toHash = function () {
    let hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
        chr = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};