« get me outta code hell

sugar: re (adapted from emnudge.dev) - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2026-03-31 07:59:55 -0300
committer(quasar) nebula <qznebula@protonmail.com>2026-03-31 08:00:07 -0300
commitab8ab50387fa3a129d59f5e4fe7c221b987955d7 (patch)
tree757faee86b12b9722e5979d73ac928b49d5091e7 /src
parent4dc4cfcfe321d6a7772369f34dd73865389105ac (diff)
sugar: re (adapted from emnudge.dev)
Diffstat (limited to 'src')
-rw-r--r--src/common-util/sugar.js36
1 files changed, 36 insertions, 0 deletions
diff --git a/src/common-util/sugar.js b/src/common-util/sugar.js
index 354cf5cc..4dd34785 100644
--- a/src/common-util/sugar.js
+++ b/src/common-util/sugar.js
@@ -417,6 +417,42 @@ export function escapeRegex(string) {
   return string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
 }
 
+// Adapted from here: https://emnudge.dev/notes/multiline-regex/
+export function re(...args) {
+  let flags = '';
+
+  const fn = (strings, ...substitutions) => {
+    strings = strings
+      .map(str => str.replace(/(?:\/\/.+)/gm, ''))
+      .map(str => str.replace(/\s+/g, ''));
+
+    substitutions = substitutions
+      .map(sub => [sub].flat(Infinity))
+      .map(sub => sub
+        .map(item =>
+          (item instanceof RegExp
+            ? item.source
+            : item.toString())))
+      .map(sub => sub.join(''));
+
+    const source =
+      String.raw({raw: strings}, ...substitutions);
+
+    return new RegExp(source, flags);
+  };
+
+  if (
+    args.length === 1 &&
+    typeof args[0] === 'string' &&
+    args[0].match(/^[a-z]+$/)
+  ) {
+    flags = args[0];
+    return fn;
+  } else {
+    return fn(...args);
+  }
+}
+
 export function splitKeys(key) {
   return key.split(/(?<=(?<!\\)(?:\\\\)*)\./);
 }