diff options
| 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 |
| commit | ab8ab50387fa3a129d59f5e4fe7c221b987955d7 (patch) | |
| tree | 757faee86b12b9722e5979d73ac928b49d5091e7 /src/common-util | |
| parent | 4dc4cfcfe321d6a7772369f34dd73865389105ac (diff) | |
sugar: re (adapted from emnudge.dev)
Diffstat (limited to 'src/common-util')
| -rw-r--r-- | src/common-util/sugar.js | 36 |
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(/(?<=(?<!\\)(?:\\\\)*)\./); } |