summaryrefslogtreecommitdiffstats
path: root/theme/javascript/utils/path.js
blob: 2f4c49ed4fe67bcda7aad9e5e656e175e0ac1033 (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
define([], function() {
    // Joins path segments.  Preserves initial "/" and resolves ".." and "."
    // Does not support using ".." to go above/outside the root.
    // This means that join("foo", "../../bar") will not resolve to "../bar"
    function join(/* path segments */) {
        // Split the inputs into a list of path commands.
        var parts = [];
        for (var i = 0, l = arguments.length; i < l; i++) {
            parts = parts.concat(arguments[i].split("/"));
        }
        // Interpret the path commands to get the new resolved path.
        var newParts = [];
        for (i = 0, l = parts.length; i < l; i++) {
            var part = parts[i];
            // Remove leading and trailing slashes
            // Also remove "." segments
            if (!part || part === ".") continue;
            // Interpret ".." to pop the last segment
            if (part === "..") newParts.pop();
            // Push new path segments.
            else newParts.push(part);
        }
        // Preserve the initial slash if there was one.
        if (parts[0] === "") newParts.unshift("");
        // Turn back into a single string path.
        return newParts.join("/") || (newParts.length ? "/" : ".");
    }
     
    // A simple function to get the dirname of a path
    // Trailing slashes are ignored. Leading slash is preserved.
    function dirname(path) {
        return join(path, "..");
    }

    // test if a path or url is absolute
    function isAbsolute(path) {
        if (!path) return false;

        return (path[0] == "/" || path.indexOf("http://") == 0 || path.indexOf("https://") == 0);
    }

    return {
        dirname: dirname,
        join: join,
        isAbsolute: isAbsolute
    };
})