Using JavaScript ES5, I would like to know if you could suggest me a more "elegant" and succinct way to overriding defaults variable when User pass custom values.
In the following example, an animation is executed using _defaultOptions
, a developer can change the default behavior passing only some properties to a function, example:
animate(dom, {duration: 2000}); // overriding only duration, rest as default
Notes:
- I need also to support IE 11.
optionsArg
is optional, soanimate(dom)
is allowed
var dom = document.getElementById('logo');
var _defaultOptions = {
duration: 1000,
delay: 0,
iterations: 1,
direction: 'normal',
fill: 'both'
};
var animate = function(dom, optionsArg) {
// code to be improved here
var options = {
duration: optionsArg && 'duration' in optionsArg ? optionsArg.duration : _defaultOptions.duration,
delay: optionsArg && 'delay' in optionsArg ? optionsArg.delay : _defaultOptions.delay,
iterations: optionsArg && 'iterations' in optionsArg ? optionsArg.iterations : _defaultOptions.iterations,
direction: optionsArg && 'direction' in optionsArg ? optionsArg.direction : _defaultOptions.direction,
fill: optionsArg && 'fill' in optionsArg ? optionsArg.fill : _defaultOptions.fill,
};
dom.animate([{
opacity: 1
}, {
opacity: 0
}], options);
};
animate(dom, {duration: 2000});
<img id="logo" src="https://upload.wikimedia.org/wikipedia/commons/e/e5/NASA_logo.svg">