From 2afcffb30a69d1a6f41f90a9214199f1c45a2516 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Mon, 7 Dec 2009 23:36:31 -0500 Subject: [PATCH] added guards to _.first and _.rest and tests, they now work as function parameters to _.map --- test/arrays.js | 4 ++++ underscore.js | 16 +++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/test/arrays.js b/test/arrays.js index 3b0ad20a1..9eb8dac54 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -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() { diff --git a/underscore.js b/underscore.js index 5d781fe6f..2f3b025ea 100644 --- a/underscore.js +++ b/underscore.js @@ -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; }); };