Skip to content

Instantly share code, notes, and snippets.

@getify
Last active April 3, 2020 15:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/eb5bb0c50de7484c4ae6e5e4dbd634be to your computer and use it in GitHub Desktop.
Save getify/eb5bb0c50de7484c4ae6e5e4dbd634be to your computer and use it in GitHub Desktop.
"destructuring + restructuring": merging objects with defaults using destructuring instead of `extend(..)`
// most common approach, using extend(..)
var defaults = {
url: "http://some.base.url/api",
method: "post",
headers: [
"Content-Type: text/plain"
]
};
console.log(defaults);
// ************************
var settings = {
url: "http://some.other.url/",
data: 42,
callback: function(resp) { /* .. */ }
};
// underscore extend(..)
ajax( _.extend({},defaults,settings) );
// or: ajax( Object.assign({},defaults,settings) );
// instead, IMO better using destructuring and defaults
var defaults = ajaxOptions(); // with no arguments, returns the defaults as an object if necessary
console.log(defaults);
// ************************
var settings = {
url: "http://some.other.url/",
data: 42,
callback: function(resp) { /* .. */ }
};
ajax( ajaxOptions( settings ) ); // with an argument, mixes in the settings w/ the defaults
// ************************
function ajaxOptions({
url = "http://some.base.url/api",
method = "post",
data,
callback,
headers: [
headers0 = "Content-Type: text/plain",
...otherHeaders
] = []
} = {}) {
return {
url, method, data, callback,
headers: [
headers0,
...otherHeaders
]
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment