« get me outta code hell

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
diff options
context:
space:
mode:
Diffstat (limited to 'extension/lib.js')
-rw-r--r--extension/lib.js34
1 files changed, 34 insertions, 0 deletions
diff --git a/extension/lib.js b/extension/lib.js
new file mode 100644
index 0000000..acb5057
--- /dev/null
+++ b/extension/lib.js
@@ -0,0 +1,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;
+}