Created
November 5, 2021 21:54
-
-
Save jberger/77d04bef92bb2979cf05d35c1475cbab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/src/util.ts b/src/util.ts | |
index c6e68b3..23e9b93 100644 | |
--- a/src/util.ts | |
+++ b/src/util.ts | |
@@ -130,6 +130,14 @@ export function decodeURIComponentSafe(value: string): string | null { | |
} | |
} | |
+export function defaultObject<Type>(defaultValue: Type): Record<string, Type> { | |
+ return new Proxy({}, { | |
+ get: function(target: Record<string, Type>, name: string) { | |
+ return target[name] ?? defaultValue; | |
+ }, | |
+ }); | |
+} | |
+ | |
export function escapeRegExp(string: string) { | |
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | |
} | |
diff --git a/test/util.js b/test/util.js | |
index bd86a92..611e478 100644 | |
--- a/test/util.js | |
+++ b/test/util.js | |
@@ -255,4 +255,12 @@ t.test('Util', async t => { | |
t.equal(tablify([[1], [], [2, 3]]), '1\n\n2 3\n'); | |
t.end(); | |
}); | |
+ | |
+ t.test('defaultObject', t => { | |
+ const foo = util.defaultObject('foo'); | |
+ foo.bar = 'bar'; | |
+ t.equal(foo.foo, 'foo'); | |
+ t.equal(foo.bar, 'bar'); | |
+ t.end(); | |
+ }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment