根据underscore精简的函数(集合篇)

这里将underscore.js内的函数进行精简,指在帮助理解或者快速回忆起underscore.js的原理,更深入的了解函数式编程。

本文基于underscore.js1.8.3版本,参考手册为
http://www.css88.com/doc/underscore/

_.each

function each(arr,iteratee){
    for(i=0,length=arr.length;ireturn arr;
}

var a=[1,2,3];
var b=each(a,function(value){
    console.log(value);
});
console.log(b);

运行结果

1
2
3

_.map

function map(arr,iteratee){
    var length=arr.length,
        results=Array(length);
    for(var index=0;indexreturn results;
}

var array=[12,5,2,4,6,13,12];
var a=map(array,function(value){
    return value*2;
});

运行结果

[ 24, 10, 4, 8, 12, 26, 24 ]

_.reduce

var createReduce=function(dir){
    var reducer=function(arr,iteratee,memo,initial){
        var length=arr.length,
            index=dir>0?0:length-1;
        if(!initial){
            memo=arr[index];
            index+=dir;
        }
        for(;index>=0&&indexreturn memo;
    };
    return function(arr,iteratee,memo,context){
        var initial=arguments.length>=3;
        return reducer(arr,iteratee,memo,initial);
    };
};

reduce=createReduce(1);
var sum = reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
console.log(sum);

运行结果

6

_.reduceRight

var createReduce=function(dir){
    var reducer=function(arr,iteratee,memo,initial){
        var length=arr.length,
            index=dir>0?0:length-1;
        if(!initial){
            memo=arr[index];
            index+=dir;
        }
        for(;index>=0&&indexreturn memo;
    };
    return function(arr,iteratee,memo,context){
        var initial=arguments.length>=3;
        return reducer(arr,iteratee,memo,initial);
    };
};

reduceRight=createReduce(-1);
var list = [[0, 1], [2, 3], [4, 5]];
var flat = reduceRight(list, function(a, b) { return a.concat(b); }, []);
console.log(flat);

运行结果

[ 4, 5, 2, 3, 0, 1 ]

_.filter

function filter(arr,predicate){
    var results=[];
    each (arr,function(value,index,list){
        if (predicate(value,index,list))results.push(value);
    });
    return results;
}

var array=[12,5,2,4,6,13,12];
var morethan10=filter(array,function(elem){
    return elem>10;
});
console.log(morethan10);

运行结果

[ 12, 13, 12 ]

_.reject

function negate(predicate){
    return function(){
        return !predicate.apply(this,arguments);
    }
}
var reject=function(arr,predicate){
    return filter(arr,negate(predicate));
};

var array=[12,5,2,4,6,13,12];
var lessthan10=reject(array,function(elem){
    return elem>10;
});
console.log(lessthan10);

运行结果

[ 5, 2, 4, 6 ]

_.every

function every(arr,predicate){
    for(let i=0;iif(!predicate(arr[i],i,arr)) return false;
    }
    return true;
}

var array=[12,5,2,4,6,13,12];
var lessthan10=every(array,function(elem){
    return elem>1;
});
console.log(lessthan10);

运行结果

true

_.some

function some(arr,predicate){
    for(let i=0;iif(predicate(arr[i],i,arr)) return true;
    }
    return false;
}

var array = [12,50,2,4,6,13,12];
var b= some(array, function(elem){
return elem<10;
});
console.log(b);

运行结果

true

_.indexOf

var createIndexFinder=function(dir){
    return function(array,item,idx){
        var i=0,length=array.length;
        if(dir>0){
            idx=0;
            i=idx>=0?idx:Math.max(idx+length,i);
        }else{
            idx=length;
            length=idx>=0?Math.min(idx+1,length):idx+length+1;
        }
        for(idx=dir>0?i:length-1;idx>=0&&idxif(array[idx]===item) return idx;
        }
        return -1;
    };
};

indexOf=createIndexFinder(1);
var a=indexOf([1,6, 2, 3,4,5], 2);
console.log(a);

运行结果

2

_.lastIndexOf

var createIndexFinder=function(dir){
    return function(array,item,idx){
        var i=0,length=array.length;
        if(dir>0){
            idx=0;
            i=idx>=0?idx:Math.max(idx+length,i);
        }else{
            idx=length;
            length=idx>=0?Math.min(idx+1,length):idx+length+1;
        }
        for(idx=dir>0?i:length-1;idx>=0&&idxif(array[idx]===item) return idx;
        }
        return -1;
    };
};

lastIndexOf=createIndexFinder(-1);
var b=lastIndexOf([1, 3, 1, 2, 3], 2);
console.log(b);

运行结果

3

_.sortedIndex

var sortedIndex=function(arr,value){
    var low=0,high=arr.length;
    while(lowvar mid=Math.floor((low+high)/2);
        if(arr[mid]1;
        else
            high=mid;
    }
    return low;
};

var a=sortedIndex([10, 20, 30, 40, 50], 35);
console.log(a);

运行结果

3

_.findIndex

var createPredicateIndexFinder=function(dir){
    return function(arr,predicate){
        var length=arr.length;
        var index=dir>0?0:length-1;
        for(;index>=0&&indexif(predicate(arr[index],index,array)) return index;
        }
        return -1;
    };
};

findIndex=createPredicateIndexFinder(1);
var a=findIndex([4, 6, 8, 12], function(value){
return value===8;
});
console.log(a);

运行结果

2

_.findLastIndex

var createPredicateIndexFinder=function(dir){
    return function(arr,predicate){
        var length=arr.length;
        var index=dir>0?0:length-1;
        for(;index>=0&&indexif(predicate(arr[index],index,array)) return index;
        }
        return -1;
    };
};

findLastIndex=createPredicateIndexFinder(-1);
var a=findLastIndex([4, 6, 8, 12, 5, 12], function(value){
return value===12;
});
console.log(a);

运行结果

5

_.findKey

var findKey=function(obj,predicate){
    var keys=Object.keys(obj);
    for(var i=0,length=keys.length;iif(predicate(obj[key],key,obj)) return key;
    }
};
var student = {
name: 'wxj',
age: 18
};
var a=findKey(student, function(value, key, obj) {
return value === 18;
});
console.log(a);

运行结果

age

_.where

function where(table,attrs){
    //遍历tale
    return table.filter(function (elem) {
        //判断当前遍历到的对象是都符合条件
        return Object.keys(attrs).every(function(attr){
            return elem[attr]===attrs[attr];
        });
    });
}
var users = [
{name: 'wxj', age: 18, sex: 'male'},
{name: 'zxy', age: 18, sex: 'male'},
{name: 'zhangsan', age: 14, sex: 'famale'}
];
var a = where(users, {age: 18, sex: 'male'});
console.log(a);

运行结果

[ { name: 'wxj', age: 18, sex: 'male' },
  { name: 'zxy', age: 18, sex: 'male' } ]

_.contains

var contains=function(arr,item,fromIndex){
    return arr.indexOf(item,fromIndex)>=0;
};
var a =contains([1, 2, 3, 4, 5], 2);
console.log(a);

运行结果

true

_.sample

function sample(set,n){
    var length=set.length;
    var i;
    var sample=set.map(function(elem){
        return elem;
    });
    if (n==void 0){
        n=1;
    }
    var last=length-1;
    for(i=0;ivar randIndex=Math.floor(Math.random()*(last-i+1)+i);
        var tmp=sample[i];
        sample[i]=sample[randIndex];
        sample[randIndex]=tmp;
    }
    return sample.slice(0,n);
}
var set=[1,2,3,4,5,6,7,8,9,10];
var a=sample(set,4);
console.log(a);

运行结果

[ 8, 9, 2, 6 ]

_.group

var group=function(behavior){
    return function(arr,iteratee){
        var result={};
        each(arr,function(value,index){
            var key=iteratee(value,index,arr);
            behavior(result,value,key);
        });
        return result;
    };
};

_.groupBy

var has=function(obj, key) {
    return obj != null && hasOwnProperty.call(obj, key);
  };
var groupBy=group(function(result,value,key){
    if (has(result, key))
      result[key].push(value);
    else result[key] = [value];
});

var a=groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });

console.log(a);

运行结果

{ '1': [ 1.3 ], '2': [ 2.1, 2.4 ] }

你可能感兴趣的:(前端)