Last active
April 11, 2024 19:00
-
-
Save darcher-/3f8fb5d3d067a6ad77355f6e88043811 to your computer and use it in GitHub Desktop.
Nullish coalescing and Map condition hash
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
/** | |
* Just an example to showcase some conditional logic | |
* | |
* Nullish coalescing operator (??) | |
* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing | |
* Nullish coalescing assignment (??=) | |
* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment | |
* Map object (new Map()) | |
* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map | |
* Map.getter (Map.get()) | |
* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | |
*/ | |
const obj = { | |
v: [1, 2, 3], | |
w: undefined, | |
x: "foo", | |
y: null, | |
z: 0, | |
}; | |
const pxy = new Proxy(obj, { | |
get(to, key) { | |
return ( | |
Object.defineProperty(to, key, { | |
value: | |
new Map([ | |
[0, "sold out"], | |
[null, "backorder"], | |
[undefined, "review"], | |
]).get(to[key] ??= Reflect.get(...arguments)) ?? to?.[key], | |
writable: true, | |
}) ?? to | |
); | |
}, | |
}); | |
/** pxy -> { | |
v: [1, 2, 3], | |
w: "review" | |
x: "foo" | |
y: "backorder" | |
z: "sold out" | |
} */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment