1
\$\begingroup\$

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, so animate(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">

\$\endgroup\$
-1
\$\begingroup\$
Object.assign(_defaultOptions, optionsArg )

But this will have side effects as it changes _defaultOptions object itself.

\$\endgroup\$
  • \$\begingroup\$ Can you clarify it? Moreover following code will not cause any side effect. Object.assign( Object.create(_defaultOptions), optionsArg ) \$\endgroup\$ – Vetrivel Jan 9 '17 at 11:10
  • \$\begingroup\$ Thanks for your answer, I am aware of Object.assign but I would need to have it also working on IE \$\endgroup\$ – GibboK Jan 9 '17 at 11:19
  • \$\begingroup\$ As mentioned in my question I need ES5 solutions Object.assign() is ES6 for my understanding. \$\endgroup\$ – GibboK Jan 9 '17 at 11:25
  • \$\begingroup\$ Yep. got it. I could simplify options to this level var options = { duration: optionsArg.duration || _defaultOptions.duration, delay: optionsArg.delay || _defaultOptions.delay, iterations: optionsArg.iterations || _defaultOptions.iterations, direction: optionsArg.direction || _defaultOptions.direction, fill: optionsArg.fill || _defaultOptions.fill, }; \$\endgroup\$ – Vetrivel Jan 9 '17 at 11:30
  • 1
    \$\begingroup\$ This doesn't even resemble a code review. Please elaborate in your 'review'. \$\endgroup\$ – Damien Roche Jan 9 '17 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.