Skip to content

Commit

Permalink
Issue jashkenas#484: _.uniq() should work with sparse arrays.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kit Cambridge committed Feb 20, 2012
1 parent 23931b2 commit c8d4025
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
22 changes: 22 additions & 0 deletions test/arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,28 @@ $(document).ready(function() {

var result = (function(){ return _.uniq(arguments); })(1, 2, 1, 3, 1, 4);
equal(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');

var list = [];
list[2] = list[3] = null;
list[8] = 2;
list[10] = 2;
list[11] = 5;
list[14] = 5;
list[16] = 8;
list[19] = 8;
list[26] = list[29] = undefined;
list[33] = "hi";

var result = _.uniq(list, true);
if (0 in [undefined]) {
// According to the JScript ES 3 spec, section 2.1.26, JScript 5.x (IE <=
// 8) treats `undefined` elements in arrays as elisions.
deepEqual(result, [null, 2, 5, 8, undefined, "hi"], "Works with sorted sparse arrays");
equal(result.length, 6, "The resulting array should not be sparse");
} else {
deepEqual(result, [null, 2, 5, 8, "hi"], "Works with sorted sparse arrays where `undefined` elements are elided");
equal(result.length, 5, "The resulting array should not be sparse");
}
});

test("arrays: intersection", function() {
Expand Down
13 changes: 6 additions & 7 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,16 +371,15 @@
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator) {
var initial = iterator ? _.map(array, iterator) : array;
var result = [];
_.reduce(initial, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
memo[memo.length] = el;
result[result.length] = array[i];
var results = [], previous;
_.reduce(iterator ? _.map(array, iterator) : array, function (memo, value, index) {
if (array.length < 3 || isSorted ? _.last(memo) !== value || !memo.length : !_.include(memo, value)) {
memo.push(previous = value);
results.push(array[index]);
}
return memo;
}, []);
return result;
return results;
};

// Produce an array that contains the union: each distinct element from all of
Expand Down

0 comments on commit c8d4025

Please sign in to comment.