0

so i'm trying my hands on writing my very first library module using pure javascript except that i just hit a snag and need a little bit of help.

I'm using Revealing module pattern because of its neatness. In my module i have my default params in an object like this.

var defaults = {
   name : 'John Doe',
   age : 'Unspecified,
   height : '5feet'
};

And this works splendid, but i have an init function where a user can pass an object with these keys. e.g

Module.init({

     name : 'james',
     age : 12
});

Now in my code, i try to write a function that returns the values of each of these keys comparing the default values and the initialized one. If the key/value exists initialized, it should return it else use default. I know what i want, but don't know how to check the objects keys just yet.

function getValues (defaultObject, initObject){

   //scans the keys and returns the values

}

So in code i can do stuff like

var options = getValues(defaultObject, initObject);
var name = options.name;

This means that name will either be james if specified or john doe if not. Also for height since i didn't set a value, i get the default too

Thanks in advance guys.

0

2 Answers 2

0

What you need to do to compare both objects keys, and if the new object has a key, then replace the value in the old one. Here's an example:

function getValues(defaultObject, initObject) {
  for (var key in initObject) {
    if (initObject.hasOwnProperty(key)) {
      defaultObject[key] = initObject[key];
    }
  }

  return defaults;
}

I hope this help you.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad I could help. Don't forget to accept the answer (for futur references)
0

See my answer in another thread how to better define function optional default params : https://stackoverflow.com/a/52082835/1422407

It may help you to redefine function signature, and as result less useless logic in function itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.