Skip to content

Instantly share code, notes, and snippets.

@jaquinocode
Last active December 25, 2023 19:46
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 jaquinocode/41a12dc90a3c6229f064f8c76de8f1c7 to your computer and use it in GitHub Desktop.
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.
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