Skip to content

Commit

Permalink
pushed all hasOwnProperty checks into _.keys, speeding _.keys up by a…
Browse files Browse the repository at this point in the history
…bout 25%, and using it to simplify other functions: _.each, _.isEmpty, _.functions
  • Loading branch information
jashkenas committed Dec 6, 2009
1 parent a97836a commit 689cd97
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,10 @@
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length) {
for (var i=0, l = obj.length; i<l; i++) iterator.call(context, obj[i], i, obj);
for (var i=0, l=obj.length; i<l; i++) iterator.call(context, obj[i], i, obj);
} else {
for (var key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
var keys = _.keys(obj), l = keys.length;
for (var i=0; i<l; i++) iterator.call(context, obj[keys[i]], keys[i], obj);
}
} catch(e) {
if (e != breaker) throw e;
Expand Down Expand Up @@ -391,7 +390,10 @@

// Retrieve the names of an object's properties.
_.keys = function(obj) {
return _.map(obj, function(value, key){ return key; });
if(_.isArray(obj)) return _.range(0, obj.length);
var keys = [];
for (var key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) keys.push(key);
return keys;
};

// Retrieve the values of an object's properties.
Expand Down Expand Up @@ -441,7 +443,7 @@

// Is a given array or object empty?
_.isEmpty = function(obj) {
return (_.isArray(obj) ? obj : _.values(obj)).length == 0;
return _.keys(obj).length == 0;
};

// Is a given value a DOM element?
Expand Down Expand Up @@ -503,9 +505,7 @@

// Return a sorted list of the function names available in Underscore.
_.functions = function() {
var functions = [];
for (var key in _) if (Object.prototype.hasOwnProperty.call(_, key)) functions.push(key);
return _.without(functions, 'VERSION', 'prototype', 'noConflict').sort();
return _.without(_.keys(_), 'VERSION', 'prototype', 'noConflict').sort();
};

// JavaScript templating a-la ERB, pilfered from John Resig's
Expand Down

0 comments on commit 689cd97

Please sign in to comment.