Skip to content

Commit

Permalink
make first() & last() useful for non-DOM collections
Browse files Browse the repository at this point in the history
Example:
  $(['a', 'b']).last()  //=> 'b'

Closes madrobby#298
  • Loading branch information
mislav committed Nov 3, 2011
1 parent 0e0245f commit 9a4be0d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/zepto.js
Expand Up @@ -217,8 +217,8 @@ var Zepto = (function() {
eq: function(idx){
return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1);
},
first: function(){ return $(this[0]) },
last: function(){ return $(this[this.length - 1]) },
first: function(){ var el = this[0]; return el && !isO(el) ? el : $(el) },
last: function(){ var el = this[this.length - 1]; return el && !isO(el) ? el : $(el) },
find: function(selector){
var result;
if (this.length == 1) result = $$(this[0], selector);
Expand Down
19 changes: 18 additions & 1 deletion test/zepto.html
Expand Up @@ -269,9 +269,12 @@ <h1>Zepto DOM unit tests</h1>
}

Evidence.Assertions.assertEqualCollection = function(expectedCollection, actualCollection, message) {
var expected = expectedCollection.get(), actual = actualCollection.get(),
var expected = expectedCollection, actual = actualCollection,
passed = expected.length == actual.length;

if (typeof expected.get == 'function') expected = expected.get();
if (typeof actual.get == 'function') actual = actual.get();

if (passed) for (var i=0; i<expected.length; i++) passed = expected[i] == actual[i];

this._assertExpression(passed, message || 'Failed assertion.',
Expand Down Expand Up @@ -318,6 +321,12 @@ <h1>Zepto DOM unit tests</h1>
t.assertLength(0, $(''));
},

testDollarWithNonDOM: function(t){
var zepto = $(['a', 'b', 'c']);
t.assertLength(3, zepto);
t.assertEqualCollection(['a', 'b', 'c'], zepto);
},

testSize: function(t){
t.assertEqual(4, $('#find1 .findme').size());
},
Expand Down Expand Up @@ -539,6 +548,10 @@ <h1>Zepto DOM unit tests</h1>
t.assertLength(0, $('nonexistent').first());
},

testFirstNonDOM: function(t){
t.assertEqual('a', $(['a', 'b', 'c']).first());
},

testLast: function(t){
var zepto = $('h1,p');
t.assertLength(5, zepto);
Expand All @@ -553,6 +566,10 @@ <h1>Zepto DOM unit tests</h1>
t.assertLength(0, $('nonexistent').last());
},

testLastNonDOM: function(t){
t.assertEqual('c', $(['a', 'b', 'c']).last());
},

testPluck: function(t){
t.assertEqual('H1DIVDIV', $('h1,div.htmltest').pluck('tagName').join(''));
},
Expand Down

0 comments on commit 9a4be0d

Please sign in to comment.