Skip to content

Commit

Permalink
Ensure _.sortBy stable sorts when iterating an object.
Browse files Browse the repository at this point in the history
  • Loading branch information
John-David Dalton committed Jul 28, 2015
1 parent 4747d4e commit 4415d62
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
15 changes: 11 additions & 4 deletions test/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@
this.y = y;
}

var collection = [
var stableArray = [
new Pair(1, 1), new Pair(1, 2),
new Pair(1, 3), new Pair(1, 4),
new Pair(1, 5), new Pair(1, 6),
Expand All @@ -644,13 +644,20 @@
new Pair(void 0, 5), new Pair(void 0, 6)
];

var actual = _.sortBy(collection, function(pair) {
var stableObject = _.object('abcdefghijklmnopqr'.split(''), stableArray);

var actual = _.sortBy(stableArray, function(pair) {
return pair.x;
});

deepEqual(actual, collection, 'sortBy should be stable');
deepEqual(actual, stableArray, 'sortBy should be stable for arrays');
deepEqual(_.sortBy(stableArray, 'x'), stableArray, 'sortBy accepts property string');

actual = _.sortBy(stableObject, function(pair) {
return pair.x;
});

deepEqual(_.sortBy(collection, 'x'), collection, 'sortBy accepts property string');
deepEqual(actual, stableArray, 'sortBy should be stable for objects');

list = ['q', 'w', 'e', 'r', 't', 'y'];
deepEqual(_.sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses _.identity if iterator is not specified');
Expand Down
7 changes: 4 additions & 3 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -380,12 +380,13 @@

// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
var index = 0;
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return _.pluck(_.map(obj, function(value, key, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
index: index++,
criteria: iteratee(value, key, list)
};
}).sort(function(left, right) {
var a = left.criteria;
Expand Down

0 comments on commit 4415d62

Please sign in to comment.