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 Answer 1

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

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

\$\endgroup\$
6
  • \$\begingroup\$ Can you clarify it? Moreover following code will not cause any side effect. Object.assign( Object.create(_defaultOptions), optionsArg ) \$\endgroup\$ Commented Jan 9, 2017 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\$ Commented Jan 9, 2017 at 11:19
  • \$\begingroup\$ As mentioned in my question I need ES5 solutions Object.assign() is ES6 for my understanding. \$\endgroup\$ Commented Jan 9, 2017 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\$ Commented Jan 9, 2017 at 11:30
  • 1
    \$\begingroup\$ This doesn't even resemble a code review. Please elaborate in your 'review'. \$\endgroup\$ Commented Jan 9, 2017 at 13:20

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.