Skip to content

Instantly share code, notes, and snippets.

@officialdavidtaylor
Last active April 2, 2025 22:19
Show Gist options
  • Save officialdavidtaylor/b7acaeed15bc24238eaf5daab3fedbdb to your computer and use it in GitHub Desktop.
Save officialdavidtaylor/b7acaeed15bc24238eaf5daab3fedbdb to your computer and use it in GitHub Desktop.
A technique for constructing a JS map object with a default return value
// example inspired by https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
const defaultKey = Symbol("default");
// a benefit of keying with a Symbol is that it is not enumerable in a for...in iteration
const map = {
key1: "foo",
key2: "bar",
[defaultKey]: "baz",
};
const trap = {
get(target, prop, receiver) {
if (prop in target) return Reflect.get(...arguments);
return target[defaultKey]
},
};
const catchAllMap = new Proxy(map, trap);
// first set of examples:
console.log(catchAllMap.key1) // "foo"
console.log(catchAllMap.key2) // "bar"
console.log(catchAllMap.key3) // "baz"
console.log(catchAllMap.anything_at_all) // "baz"
// imo, the syntax above feels a bit clunky
// wrapping it into a helper function could be quite handy
// AND it removes the need to add a Symbol key to the object
function createCatchAllMap(map, defaultValue) {
const trap = {
get(target, prop, receiver) {
if (prop in target) return Reflect.get(...arguments);
return defaultValue;
},
};
return new Proxy(map, trap);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment