Last active
December 25, 2023 19:46
-
-
Save jaquinocode/41a12dc90a3c6229f064f8c76de8f1c7 to your computer and use it in GitHub Desktop.
setdefault but for JavaScript. setdefault is a function in Python which can be used to get around using a defaultdict. Here I recreate the behavior in JavaScript.
This file contains hidden or 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
const getDefault = (o, key, defaultVal) => key in o ? o[key] : o[key] = defaultVal | |
// Prototype version of above. Allows for usage: o.getDefault(key, def) | |
Object.defineProperty(Object.prototype, "getDefault", { | |
value: function(key, defaultVal) { | |
return key in this ? this[key] : this[key] = defaultVal | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment