0
\$\begingroup\$

When iterating over the members of an object for logging the keys / values one gets a "stair case" effect. Therefore I wrote myself this function which takes care for a left-alignment of the values.

Any hints concerning flaws and improvement-recommendations welcome.

// #### START TEST #######################
var person = {
  yourMobilPhoneNumber : 01234171819,
  firstName : 'theFirstName',
  lastName : 'theLastName',
  mail : '[email protected]',
  zip : '12345',          
  street : 'theNameOfMyStreet',
  city : 'someCitySomewhere',
  yourVeryPersonalWebpage : 'http://that-is-me.com',
  id : 12345,
  calculate: function() { return 3 + 4; }
};

displayMembers(person);
// #### END TEST #######################

// Displays the members of an assigned 
//   object on the console.

// -- Parameter -------------
// Object - An object which members 
//   shall be displayed.

function displayMembers(obj) {
  var i;
  var max = (function() {
    var ret = 0;
    var keys = Object.keys(obj);

    for (i = 0; i < keys.length; i++) {
      if (keys[i].length > ret)
        ret = keys[i].length; 
    }

    return ret;
  })();

  var getSpacer = function(len, state) {

    if (state.length < len) {
      return getSpacer(len, state += ' ');
    } else {
      return state;
    }
  }

  for (i in obj) {
    console.log('%s: %s%s',
                i, 
                getSpacer(max - i.length, ''), 
                obj[i]);
  }
}  

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Simplification with for/in loops

Your loop through Object.keys() in the function you have for the max variable is reinventing JavaScript's for/in loop which loops over and objects keys. Here's how you could simplifying that code:

for(var key in obj) {
    if(!obj.hasOwnProperty(key)) {
        continue;
    }

    if(key.length > ret) {
        ret = key.length;
    }
}

Unnecessary recursion

Your getSpacer function is using recursion when it really does not need to be; the function would be a lot simpler and a lot faster if you used a neat JavaScript trick for repeating characters:

function getSpacer(len) {
    return Array(len + 1).join(" ");
}

Now, there's no need for recursion - that means there is less interaction with the stack - and, rather than switching to a loop, this nice solution can be used.

\$\endgroup\$
1
  • \$\begingroup\$ The Array.join() trick is awesome. :) Thanks a lot. \$\endgroup\$ Commented Mar 20, 2016 at 14:22

Your Answer

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

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