var C = {};
C.max = C.best = function(set,getVal,comparison) {
if(!set || !set.length) return false;
return C.creator(set,getVal,comparison,'max');
}
C.min = C.worse = function(set,getVal,comparison) {
if(!set || !set.length) return false;
return C.creator(set,getVal,comparison,'min');
}
C.creator = function(set,getVal,comparison,type) {
var ret = function(first,second,_type) {
if(_type==='max') {
return first>second ? first:second;
}
else {
return first>second ? second : first;
}
}
getVal || (getVal = function(value) { return value;});
comparison || (comparison = function(first,second) {return ret(first,second,type);})
var tmp = set[0];
var first;
var second;
var current;
for(var index=1;index<set.length;index++) {
first = getVal(tmp);
second = getVal(set[index]);
tmp = (comparison(first,second) === first) ? tmp : set[index];
}
return tmp;
}
console.log(C.max([{a:2},{a:3},{a:4},{a:13}],function(obj){return obj.a;},function(first,second){return first<second?second:first}))
对最值函数进行抽象性的编程,主要有三点:
1.传入的数据集
2.自定义取值函数
3.自定义比较规则以上代码还需要优化,需要加强边界条件的判断。