jashkenas/underscore — pull request #1606 by davidchambers (2014-04-24 21:25:44+00:00)
Title: respect iterator return value of Infinity/-Infinity in _.min/_.max

A colleague and I were just bitten by a bug in this code:

```javascript
var bestMatch = _.max(inPosteds, function(inPosted) {
// only match to posted transactions that haven't been resolved
if (inPosted._pendingTransaction) {
return -Infinity;
} else {
return pendingSimilarity(
pendingTransform(outPending),
postedTransform(inPosted)
);
}
});
```

We were surprised to discover that `bestMatch` would in some cases be -Infinity rather than an object. This results from Underscore performing `>` comparisons against an initial max of -Infinity. Since -Infinity is not greater than -Infinity, the initial value is erroneously returned if the iterator returns -Infinity for each element in a nonempty collection.

I've implemented the least invasive fix, which is to use `>=` and `<=` in place of `>` and `<`. Note that this does change undocumented behaviour not covered by the test suite: the *last* min/max element will be returned rather than the first. Consider a slightly modified version of the example from the documentation:

```javascript
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 50}];
_.max(stooges, function(stooge){ return stooge.age; });
// before => {name: 'larry', age: 50}
// after => {name: 'curly', age: 50}
```

If we wish to preserve this undocumented behaviour, I'll add appropriate test cases and adjust the implementations of _.min and _.max accordingly. This may simply involve enumerating the given collection in reverse order.