« get me outta code hell

lib.js « extension - interactive-bgm - Browser extension that adds background music based on the site you're browsing
about summary refs log tree commit diff
path: root/extension/lib.js
blob: acb50575337996703d32a072a21feea1b82c3288 (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
export function getURLParts(urlString) {
    const {hostname, pathname} = new URL(urlString);

    return {
        hostnameParts: hostname.split('.'),
        pathnameParts: pathname.slice(1).split('/').filter(Boolean)
    };
}

export function getRuleScoreOnPage(rule, urlString) {
    const {hostnameMatch, pathnameMatch} = rule;
    const {hostnameParts, pathnameParts} = getURLParts(urlString);

    // If we succeed at all, no matter how badly, the score should be non-zero!
    let score = 1;

    for (let i = 0; i < hostnameMatch.length; i++) {
        if (hostnameParts[hostnameParts.length - 1 - i] !== hostnameMatch[i]) {
            return 0;
        }

        score++;
    }

    for (let i = 0; i < pathnameMatch.length; i++) {
        if (pathnameParts[i] !== pathnameMatch[i]) {
            return 0;
        }

        score++;
    }

    return score;
}