diff --git a/index.html b/index.html index 5fb003072..22f09bc5e 100644 --- a/index.html +++ b/index.html @@ -192,7 +192,8 @@ _(lyrics).chain() Objects
keys, values, - extend, clone, isEqual, isElement, + extend, clone, + isEqual, isEmpty, isElement, isArray, isFunction, isUndefined

@@ -710,6 +711,18 @@ moe == clone; => false _.isEqual(moe, clone); => true + + +

+ isEmpty_.isEmpty(object) +
+ Returns true if object contains no values. +

+
+_.isEmpty([1, 2, 3]);
+=> false
+_.isEmpty({});
+=> true
 

diff --git a/test/objects.js b/test/objects.js index 6a20e8d9a..489c39f2a 100644 --- a/test/objects.js +++ b/test/objects.js @@ -36,6 +36,17 @@ $(document).ready(function() { ok(_(moe).isEqual(clone), 'OO-style deep equality works'); }); + test("objects: isEmpty", function() { + ok(!_([1]).isEmpty(), '[1] is not empty'); + ok(_.isEmpty([]), '[] is empty'); + ok(!_.isEmpty({one : 1}), '{one : 1} is not empty'); + ok(_.isEmpty({}), '{} is empty'); + + var obj = {one : 1}; + delete obj.one; + ok(_.isEmpty(obj), 'deleting all the keys from an object empties it'); + }); + test("objects: isElement", function() { ok(!_.isElement('div'), 'strings are not dom elements'); ok(_.isElement($('html')[0]), 'the html tag is a DOM element'); diff --git a/test/utility.js b/test/utility.js index 4022410ea..171340830 100644 --- a/test/utility.js +++ b/test/utility.js @@ -25,7 +25,7 @@ $(document).ready(function() { var expected = ["all", "any", "bind", "bindAll", "clone", "compact", "compose", "defer", "delay", "detect", "each", "every", "extend", "filter", "first", "flatten", "foldl", "foldr", "forEach", "functions", "identity", "include", - "indexOf", "inject", "intersect", "invoke", "isArray", "isElement", "isEqual", + "indexOf", "inject", "intersect", "invoke", "isArray", "isElement", "isEmpty", "isEqual", "isFunction", "isUndefined", "keys", "last", "lastIndexOf", "map", "max", "methods", "min", "pluck", "reduce", "reduceRight", "reject", "select", "size", "some", "sortBy", "sortedIndex", "template", "toArray", "uniq", diff --git a/underscore.js b/underscore.js index 692dbe905..9386b8564 100644 --- a/underscore.js +++ b/underscore.js @@ -146,9 +146,7 @@ if (_.isArray(obj)) return _.indexOf(obj, target) != -1; var found = false; _.each(obj, function(value) { - if (found = value === target) { - throw '__break__'; - } + if (found = value === target) throw '__break__'; }); return found; }; @@ -409,6 +407,11 @@ return true; }; + // Is a given array or object empty? + _.isEmpty = function(obj) { + return (_.isArray(obj) ? obj : _.values(obj)).length == 0; + }; + // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType == 1);