Skip to content

Commit

Permalink
Make Object.keys ES5 compliant.
Browse files Browse the repository at this point in the history
  • Loading branch information
tobie committed Feb 22, 2010
1 parent 038a298 commit 7eeee4f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
@@ -1,3 +1,5 @@
* Make Object.keys ES5 compliant. (Tobie Langel)

* Make Prototype's JSON implementation EcmaScript 5 compliant. [#453 state:resolved] (Tobie Langel)

* Also detect embedded (UIWebView) mobile Safari. (Thomas Fuchs)
Expand Down
30 changes: 27 additions & 3 deletions src/lang/object.js
Expand Up @@ -11,10 +11,30 @@
(function() {

var _toString = Object.prototype.toString,
NULL_TYPE = 'Null',
UNDEFINED_TYPE = 'Undefined',
BOOLEAN_TYPE = 'Boolean',
NUMBER_TYPE = 'Number',
STRING_TYPE = 'String',
OBJECT_TYPE = 'Object',
NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON &&
typeof JSON.stringify === 'function' &&
JSON.stringify(0) === '0' &&
typeof JSON.stringify(Prototype.K) === 'undefined';

function Type(o) {
switch(o) {
case null: return NULL_TYPE;
case (void 0): return UNDEFINED_TYPE;
}
var type = typeof o;
switch(type) {
case 'boolean': return BOOLEAN_TYPE;
case 'number': return NUMBER_TYPE;
case 'string': return STRING_TYPE;
}
return OBJECT_TYPE;
}

/**
* Object.extend(destination, source) -> Object
Expand Down Expand Up @@ -170,9 +190,13 @@
* normalize the order of the object keys.
**/
function keys(object) {
if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); }
var results = [];
for (var property in object)
results.push(property);
for (var property in object) {
if (object.hasOwnProperty(property)) {
results.push(property);
}
}
return results;
}

Expand Down Expand Up @@ -315,7 +339,7 @@
toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON,
toQueryString: toQueryString,
toHTML: toHTML,
keys: keys,
keys: Object.keys || keys,
values: values,
clone: clone,
isElement: isElement,
Expand Down
9 changes: 9 additions & 0 deletions test/unit/object_test.js
Expand Up @@ -23,6 +23,15 @@ new Test.Unit.Runner({
this.assertHashEqual({foo: 'foo'}, clone,
"Optimizing Object.clone perf using prototyping doesn't allow properties to be deleted.");
},

testObjectKeys: function() {
this.assertEnumEqual([], Object.keys({}));
this.assertEnumEqual(['bar', 'foo'], Object.keys({foo: 'foo', bar: 'bar'}).sort());
function Foo() { this.bar = 'bar'; }
Foo.prototype.foo = 'foo';
this.assertEnumEqual(['bar'], Object.keys(new Foo()));
this.assertRaise('TypeError', function(){ Object.keys() });
},

testObjectInspect: function() {
this.assertEqual('undefined', Object.inspect());
Expand Down

0 comments on commit 7eeee4f

Please sign in to comment.