« get me outta code hell

data-checks, sugar: factor out getNestedProp - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/util
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2024-02-16 16:11:13 -0400
committer(quasar) nebula <qznebula@protonmail.com>2024-02-17 17:09:18 -0400
commitb7debd668d03b2236cea1b0291acb8efc6f3ee0d (patch)
tree6a3825d7d489b9f9d41d1e579090c4994cd2395a /src/util
parent74ded573b9e24b120573a3f5319de7501b17a759 (diff)
data-checks, sugar: factor out getNestedProp
Diffstat (limited to 'src/util')
-rw-r--r--src/util/sugar.js13
1 files changed, 12 insertions, 1 deletions
diff --git a/src/util/sugar.js b/src/util/sugar.js
index 58a2c3e9..3c364ee5 100644
--- a/src/util/sugar.js
+++ b/src/util/sugar.js
@@ -263,11 +263,22 @@ export function delay(ms) {
 // Stolen from here: https://stackoverflow.com/a/3561711
 //
 // There's a proposal for a native JS function like this, 8ut it's not even
-// past stage 1 yet: https://github.com/tc39/proposal-regex-escaping
+// past stage ~~1~~ 2 yet: https://github.com/tc39/proposal-regex-escaping
 export function escapeRegex(string) {
   return string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
 }
 
+// Follows a key path like 'foo.bar.baz' to get an item nested deeply inside
+// an object.
+export function getNestedProp(obj, key) {
+  const recursive = (o, k) =>
+    (k.length === 1
+      ? o[k[0]]
+      : recursive(o[k[0]], k.slice(1)));
+
+  return recursive(obj, key.split(/(?<=(?<!\\)(?:\\\\)*)\./));
+}
+
 // Gets the "look" of some arbitrary value. It's like typeof, but smarter.
 // Don't use this for actually validating types - it's only suitable for
 // inclusion in error messages.