added guards to _.first and _.rest and tests, they now work as function parameters to _.map

This commit is contained in:
Jeremy Ashkenas
2009-12-07 23:36:31 -05:00
parent 21e0cbc229
commit 2afcffb30a
2 changed files with 13 additions and 7 deletions

View File

@@ -8,6 +8,8 @@ $(document).ready(function() {
equals(_.first([1,2,3], 2).join(', '), '1, 2', 'can pass an index to first');
var result = (function(){ return _.first(arguments); })(4, 3, 2, 1);
equals(result, 4, 'works on an arguments object.');
result = _.map([[1,2,3],[1,2,3]], _.first);
equals(result.join(','), '1,1', 'works well with _.map');
});
test("arrays: rest", function() {
@@ -16,6 +18,8 @@ $(document).ready(function() {
equals(_.rest(numbers, 2).join(', '), '3, 4', 'rest can take an index');
var result = (function(){ return _(arguments).tail(); })(1, 2, 3, 4);
equals(result.join(', '), '2, 3, 4', 'aliased as tail and works on arguments object');
result = _.map([[1,2,3],[1,2,3]], _.rest);
equals(_.flatten(result).join(','), '2,3,2,3', 'works well with _.map');
});
test("arrays: last", function() {

View File

@@ -229,16 +229,18 @@
/*-------------------------- Array Functions: ------------------------------*/
// Get the first element of an array. Passing "n" will return the first N
// values in the array. Aliased as "head".
_.first = function(array, n) {
return n ? Array.prototype.slice.call(array, 0, n) : array[0];
// values in the array. Aliased as "head". The "guard" check allows it to work
// with _.map.
_.first = function(array, n, guard) {
return n && !guard ? Array.prototype.slice.call(array, 0, n) : array[0];
};
// Returns everything but the first entry of the array. Aliased as "tail".
// Especially useful on the arguments object. Passing an "index" will return
// the rest of the values in the array from that index onward.
_.rest = function(array, index) {
return Array.prototype.slice.call(array, _.isUndefined(index) ? 1 : index);
// the rest of the values in the array from that index onward. The "guard"
//check allows it to work with _.map.
_.rest = function(array, index, guard) {
return Array.prototype.slice.call(array, _.isUndefined(index) || guard ? 1 : index);
};
// Get the last element of an array.
@@ -270,7 +272,7 @@
// been sorted, you have the option of using a faster algorithm.
_.uniq = function(array, isSorted) {
return _.reduce(array, [], function(memo, el, i) {
if (0 == i || (isSorted ? _.last(memo) != el : !_.include(memo, el))) memo.push(el);
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo.push(el);
return memo;
});
};