make the new faster isEmpty a little safer too

This commit is contained in:
Jeremy Ashkenas
2010-02-24 12:43:57 -05:00
parent 2c8fbe7875
commit 7824d63ce8
3 changed files with 90 additions and 90 deletions

View File

@@ -4,7 +4,6 @@
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Underscore.js</title>
<script src="underscore.js"></script>
<style>
body {
font-size: 16px;
@@ -1288,5 +1287,8 @@ _([1, 2, 3]).value();
</div>
<!-- Include Underscore, so you can play with it in the console. -->
<script type="text/javascript" src="underscore.js"></script>
</body>
</html>

View File

@@ -60,6 +60,7 @@ $(document).ready(function() {
ok(_.isEmpty([]), '[] is empty');
ok(!_.isEmpty({one : 1}), '{one : 1} is not empty');
ok(_.isEmpty({}), '{} is empty');
ok(_.isEmpty(new RegExp('')), 'objects with prototype properties are empty');
ok(_.isEmpty(null), 'null is empty');
ok(_.isEmpty(), 'undefined is empty');
@@ -102,7 +103,7 @@ $(document).ready(function() {
ok(_.isArguments(args), 'but the arguments object is an arguments object');
ok(!_.isArguments(_.toArray(args)), 'but not when it\'s converted into an array');
ok(!_.isArguments([1,2,3]), 'and not vanilla arrays.');
ok(_.isArguments(iArguments), 'event from another frame');
ok(_.isArguments(iArguments), 'even from another frame');
});
test("objects: isArray", function() {

View File

@@ -67,8 +67,7 @@
// The cornerstone, an each implementation.
// Handles objects implementing forEach, arrays, and raw objects.
// Delegates to JavaScript 1.6's native forEach if available.
var each =
_.forEach = function(obj, iterator, context) {
var each = _.forEach = function(obj, iterator, context) {
var index = 0;
try {
if (obj.forEach === nativeForEach) {
@@ -76,9 +75,9 @@
} else if (_.isNumber(obj.length)) {
for (var i = 0, l = obj.length; i < l; i++) iterator.call(context, obj[i], i, obj);
} else {
for (var key in obj)
if (hasOwnProperty.call(obj, key))
iterator.call(context, obj[key], key, obj);
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) iterator.call(context, obj[key], key, obj);
}
}
} catch(e) {
if (e != breaker) throw e;
@@ -513,7 +512,7 @@
// Is a given array or object empty?
_.isEmpty = function(obj) {
if (_.isArray(obj)) return obj.length === 0;
for (var k in obj) return false;
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
return true;
};
@@ -588,11 +587,9 @@
return value;
};
// run a function n times.
// looks good in wrapper form:
// _(3).times(alert)
_.times = function (n, fn, context) {
for (var i = 0; i < n; i++) fn.call(context, i);
// Run a function n times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Break out of the middle of an iteration.