Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
add .minmax(). Closes #12
  • Loading branch information
tj committed Dec 17, 2012
1 parent 85b1ee9 commit 6bf0f01
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
73 changes: 73 additions & 0 deletions index.js
Expand Up @@ -506,6 +506,79 @@ proto.max = function(fn){
return max;
};

/**
* Determine the min value.
*
* With a callback function:
*
* pets.min(function(pet){
* return pet.age
* })
*
* With property strings:
*
* pets.min('age')
*
* With immediate values:
*
* nums.min()
*
* @param {Function|String} fn
* @return {Number}
* @api public
*/

proto.min = function(fn){
var val;
var n = 0;
var min = Infinity;
var vals = this.__iterate__();
var len = vals.length();

if (fn) {
fn = toFunction(fn);
for (var i = 0; i < len; ++i) {
n = fn(vals.get(i), i);
min = n < min ? n : min;
}
} else {
for (var i = 0; i < len; ++i) {
n = vals.get(i);
min = n < min ? n : min;
}
}

return min;
};

/**
* Determine the min/max values.
*
* With a callback function:
*
* pets.minmax(function(pet){
* return pet.age
* })
*
* With property strings:
*
* pets.minmax('age')
*
* With immediate values:
*
* nums.minmax()
*
* @param {Function|String} fn
* @return {Number}
* @api public
*/

proto.minmax = function(fn){
var min = this.min(fn);
var max = this.max(fn);
return [min, max];
};

/**
* Determine the sum.
*
Expand Down
33 changes: 33 additions & 0 deletions test/index.js
Expand Up @@ -133,6 +133,7 @@ describe('.max()', function(){
it('should return the max value', function(){
_([1,2,3,4,5,2,1]).max().should.equal(5);
})

it('should support negative inputs', function(){
_([-1,-2,-3,-4,-5,-2,-1]).max().should.equal(-1);
})
Expand All @@ -152,6 +153,38 @@ describe('.max(fn)', function(){
})
})

describe('.min()', function(){
it('should return the min value', function(){
_([1,2,3,4,5,2,1]).min().should.equal(1);
})

it('should support negative inputs', function(){
_([-1,-2,-3,-4,-5,-2,-1]).min().should.equal(-5);
})
})

describe('.min(str)', function(){
it('should return the min property value', function(){
_([{ age: 5 }, { age: 2 }]).min('age').should.equal(2);
})
})

describe('.min(fn)', function(){
it('should return the min value', function(){
_([{ age: 5 }, { age: 2 }]).min(function(pet){
return pet.age;
}).should.equal(2);
})
})

describe('.minmax()', function(){
it('should a tuple', function(){
var arr = [1,2,3,4,5,6,5,3,2];
var ret = _(arr).minmax();
ret.should.eql([1,6]);
})
})

describe('.select(fn)', function(){
it('should select values of truthy return', function(){
_([1,2,3,4,5]).select(function(n){
Expand Down

0 comments on commit 6bf0f01

Please sign in to comment.