aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/utils/is.js
blob: cb2c07c6861b6f418ee50f67caf7ec2fff7b5307 (plain)
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
// ==========================================================================
// Type checking utils
// ==========================================================================

const getConstructor = input => (input !== null && typeof input !== 'undefined' ? input.constructor : null);

const instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);

const is = {
    object(input) {
        return getConstructor(input) === Object;
    },
    number(input) {
        return getConstructor(input) === Number && !Number.isNaN(input);
    },
    string(input) {
        return getConstructor(input) === String;
    },
    boolean(input) {
        return getConstructor(input) === Boolean;
    },
    function(input) {
        return getConstructor(input) === Function;
    },
    array(input) {
        return !is.nullOrUndefined(input) && Array.isArray(input);
    },
    weakMap(input) {
        return instanceOf(input, WeakMap);
    },
    nodeList(input) {
        return instanceOf(input, NodeList);
    },
    element(input) {
        return instanceOf(input, Element);
    },
    textNode(input) {
        return getConstructor(input) === Text;
    },
    event(input) {
        return instanceOf(input, Event);
    },
    cue(input) {
        return instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);
    },
    track(input) {
        return instanceOf(input, TextTrack) || (!is.nullOrUndefined(input) && is.string(input.kind));
    },
    url(input) {
        return (
            !is.nullOrUndefined(input) &&
            /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/.test(input)
        );
    },
    nullOrUndefined(input) {
        return input === null || typeof input === 'undefined';
    },
    empty(input) {
        return (
            is.nullOrUndefined(input) ||
            ((is.string(input) || is.array(input) || is.nodeList(input)) && !input.length) ||
            (is.object(input) && !Object.keys(input).length)
        );
    },
};

export default is;