Skip to content

Commit

Permalink
Combine _.min and _.max
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell committed Apr 8, 2015
1 parent 483fc0f commit d7ca1c1
Showing 1 changed file with 20 additions and 43 deletions.
63 changes: 20 additions & 43 deletions underscore.js
Expand Up @@ -277,56 +277,33 @@
return _.find(obj, _.matcher(attrs));
};

// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
// Generator function to create the max and min functions
var createExtremumFinder = function(max) {
return function(obj, iteratee, context) {
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
result = max ? -Infinity : Infinity,
lastComputed = result,
found = false;
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
var value = obj[currentKey];
var computed = iteratee ? iteratee(value, currentKey, obj) : value;
if ((max ? computed > lastComputed : computed < lastComputed) || (!found && computed === result)) {
found = true;
result = value;
lastComputed = computed;
}
});
}
return result;
};

// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
return result;
};
};

// Return the extremum element (or element-based computation).
_.max = createExtremumFinder(true);
_.min = createExtremumFinder(false);

// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
Expand Down

0 comments on commit d7ca1c1

Please sign in to comment.