-
-
Save getify/eb5bb0c50de7484c4ae6e5e4dbd634be to your computer and use it in GitHub Desktop.
"destructuring + restructuring": merging objects with defaults using destructuring instead of `extend(..)`
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
// 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) ); |
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
// 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