added an isEmpty function that works on arrays and objects

This commit is contained in:
Jeremy Ashkenas
2009-11-07 23:04:18 -05:00
parent d4f6e1a42f
commit b5920e94a3
4 changed files with 32 additions and 5 deletions

View File

@@ -192,7 +192,8 @@ _(lyrics).chain()
<b>Objects</b>
<br />
<span class="methods"><a href="#keys">keys</a>, <a href="#values">values</a>,
<a href="#extend">extend</a>, <a href="#clone">clone</a>, <a href="#isEqual">isEqual</a>, <a href="#isElement">isElement</a>,
<a href="#extend">extend</a>, <a href="#clone">clone</a>,
<a href="#isEqual">isEqual</a>, <a href="#isEmpty">isEmpty</a>, <a href="#isElement">isElement</a>,
<a href="#isArray">isArray</a>, <a href="#isFunction">isFunction</a>, <a href="#isUndefined">isUndefined</a>
</span>
</p>
@@ -710,6 +711,18 @@ moe == clone;
=&gt; false
_.isEqual(moe, clone);
=&gt; true
</pre>
<p id="isEmpty">
<b class="header">isEmpty</b><code>_.isEmpty(object)</code>
<br />
Returns <i>true</i> if <b>object</b> contains no values.
</p>
<pre>
_.isEmpty([1, 2, 3]);
=&gt; false
_.isEmpty({});
=&gt; true
</pre>
<p id="isElement">

View File

@@ -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');

View File

@@ -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",

View File

@@ -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);