Skip to content

Use ES5 built-in function Object.keys -- Don't replace it #3

@GarrettS

Description

@GarrettS

PrototypeJS defines Object.keys without considering if it is already defined. Instead, it should use the built-in standard, where available:

Prototype 1.6.1:
function keys(object) {
var results = [];
for (var property in object)
results.push(property);
return results;
}

ES5 requires Object.keys TypeError to be thrown there. The for-in loop is required to throw in the same case, where the object is not an object, however for web compat, browsers don't do that. Regardless, for Object.keys(9), Chrome throws.

Instead of calling push, it is faster to increment a variable.

  Object.keys = Object.keys || keys;
 
  function keys(object) {
    if(!(object instanceof Object)) {
      throw TypeError("Object.keys called on non-object");
    }
    var results = [], property, i = 0;
// Preset length, where available.
    results.length = object.__count__ || 0; 
    for (property in object)
  // faster than push()
      results[i++] = property;
    return results;
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions