2
\$\begingroup\$

I need to round numeric values for properties of a given object. The following code works fine, but I am concerned if there is a way to make it faster.

I am targeting latest Chrome and Firefox.

http://jsbin.com/bahedegoni/edit?html,output

window.app = {
            start: function () {
                var cmd = {
                    a: 11.12,
                    b: 0.29,
                    c: 'x',
                    d: 'y'
                };
                Object.keys(cmd).forEach(function (prop) {
                    if (typeof cmd[prop] === 'number') {
                        cmd[prop] = Math.round(cmd[prop]);
                    }

                }.bind(this));
                console.log(cmd);
            }
        };
\$\endgroup\$
4
  • 1
    \$\begingroup\$ This seems like a really strange thing to do. What's the context? \$\endgroup\$ – Veedrac Jun 23 '15 at 13:32
  • \$\begingroup\$ Thanks for your comment. In my specific case, cmd properties will be populated with different values including from a IDOMClientRect result.I need to round those value as only integer. \$\endgroup\$ – GibboK Jun 24 '15 at 9:23
  • \$\begingroup\$ What is cmd, though? \$\endgroup\$ – Veedrac Jun 24 '15 at 9:26
  • \$\begingroup\$ In my real app, cmd is an object which contains values for position related DOM modification. Like cmd.top = 10 which will be translate to a CSS style top position on a DOM element of 10. There is no sense in setting CSS properties to not integer values when the unit is pixel, so this is the reasons for code :). \$\endgroup\$ – GibboK Jun 24 '15 at 9:34
2
\$\begingroup\$

There's no reason to use bind; you don't rely on this anywhere in the code, so it doesn't matter what the this-context is.

Secondly, the "original" way to iterate objects in JavaScript is to use a for...in loop. However, it will also iterate inherited properties, so it's good practice to check if the key's the object's own key by using hasOwnProperty. The basic construction looks like so:

var key;
for(key in object) {
  if(!obj.hasOwnProperty(key)) continue; // skip inherited properties
  // ... do something
}

Thirdly, due to the way JavaScript expresses a NaN (Not A Number) value, it turns out that typeof NaN === 'number'. Of course, it doesn't really matter here since Math.round(NaN) is still NaN.

Point is, this would probably be one of the simplest implementations:

var key;
for(key in cmd) {
  if(obj.hasOwnProperty(key) && typeof cmd[key] === 'number') {
    cmd[key] = Math.round(cmd[key]);
  }
}
\$\endgroup\$

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.