Skip to content

Instantly share code, notes, and snippets.

@gorillamoe
Created December 29, 2016 11:19
Show Gist options
  • Save gorillamoe/e769f874a01faee3e12bdca2c13af090 to your computer and use it in GitHub Desktop.
Save gorillamoe/e769f874a01faee3e12bdca2c13af090 to your computer and use it in GitHub Desktop.
Sane handling of default opts
/*jshint esversion: 6 */
// Meet the AwesomeClass
class AwesomeClass {
constructor(opts) {
}
static defaultOpts(opts, default_opts) {
var new_opts = default_opts;
if (opts) {
for (var property in default_opts) {
if (default_opts.hasOwnProperty(property)) {
if (typeof default_opts[property] === 'object') {
new_opts[property] = this.defaultOpts(opts[property], default_opts[property]);
}
else {
if (opts[property]) { // passed opts has it
new_opts[property] = opts[property];
} else { // using default opts
new_opts[property] = default_opts[property];
}
}
}
}
}
return new_opts;
}
}
// Have you seen something like this before?
var tiresomeExampleFunction = (opts) {
opts = opts || {};
opts.id = opts.id || 1;
opts.name = opts.name || 'Yzzi';
opts.coords = opts.coords || {};
opts.coords.x = opts.coords.x || 200;
opts.coords.y = opts.coords.y || 400;
console.log(opts);
};
// just to make sure this here works..
tiresomeExampleFunction({
name: 'Ysragh Heiden',
coords: {
x: 300
}
});
// It would be nice if you can do something like this,
// tho achieve the exact same behaviour as above:
var niceExampleFunction = (opts) {
opts = AwesomeClass.defaultOpts(opts, {
id: 1,
name: 'Yzzi',
coords: {
x: 200,
y: 400
}
});
console.log(opts);
};
niceExampleFunction({
name: 'Ysragh Heiden',
coords: {
x: 300
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment