Skip to content

Instantly share code, notes, and snippets.

@jberger
Created November 5, 2021 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/77d04bef92bb2979cf05d35c1475cbab to your computer and use it in GitHub Desktop.
Save jberger/77d04bef92bb2979cf05d35c1475cbab to your computer and use it in GitHub Desktop.
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