Skip to content

respect iterator return value of Infinity/-Infinity in _.min/_.max #1606

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 28, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions test/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,11 @@

equal(3, _.max([1, 2, 3, 'test']), 'Finds correct max in array starting with num and containing a NaN');
equal(3, _.max(['test', 1, 2, 3]), 'Finds correct max in array starting with NaN');

var a = {x: -Infinity};
var b = {x: -Infinity};
var iterator = function(o){ return o.x; };
equal(_.max([a, b], iterator), a, 'Respects iterator return value of -Infinity');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test ensures that the first element in the list is returned.

});

test('min', function() {
Expand All @@ -321,6 +326,11 @@

equal(1, _.min([1, 2, 3, 'test']), 'Finds correct min in array starting with num and containing a NaN');
equal(1, _.min(['test', 1, 2, 3]), 'Finds correct min in array starting with NaN');

var a = {x: Infinity};
var b = {x: Infinity};
var iterator = function(o){ return o.x; };
equal(_.min([a, b], iterator), a, 'Respects iterator return value of Infinity');
});

test('sortBy', function() {
Expand Down
4 changes: 2 additions & 2 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@
} else {
_.each(obj, function(value, index, list) {
computed = iterator ? iterator.call(context, value, index, list) : value;
if (computed > lastComputed) {
if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The result === -Infinity check ensures we return the first value for which the iterator returns -Infinity should the iterator return -Infinity for every value.

result = value;
lastComputed = computed;
}
Expand All @@ -255,7 +255,7 @@
} else {
_.each(obj, function(value, index, list) {
computed = iterator ? iterator.call(context, value, index, list) : value;
if (computed < lastComputed) {
if (computed < lastComputed || (computed === Infinity && result === Infinity)) {
result = value;
lastComputed = computed;
}
Expand Down