lynxerzhang / JSSkills

MIT License
0 stars 0 forks source link

array的handle array方法使用记录 #14

Open lynxerzhang opened 6 years ago

lynxerzhang commented 6 years ago
@see https://github.com/Chalarangelo/30-seconds-of-code
//indexOfAll
var indexOfAll = (function(){
    return function(ary, val) {
        return ary.reduce(function(prev, cur, i){
            return cur === val ? prev.concat(i) : prev;
        }, []);
    }
})();
indexOfAll([1, 2, 3, 1, 2, 3], 1); 
// [0,3]

//getLongItem
var getLongItem = (function(){
    return function (val){
        var c = arguments.length - 1;
        var list = [val];
        if(c > 0){
            for(var i = 0; i < c; i ++){
                list.push(arguments[i + 1]);
            }
        }
        return list.reduce(function(prev, current){
            return current.length > prev.length ? current : prev;
        });
    }
})();
getLongItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); 
// [1, 2, 3, 4, 5]

//mapObject
var mapObject = (function(){
    return function(ary, keyFunc, valueFunc) {
        var d = [ary.map(keyFunc), ary.map(valueFunc)];
        return d[0].reduce(function(prev, current, index){
            return prev[current] = d[1][index], prev;
        }, {});
    }
})();
var result = mapObject(["a1+1", "a2+2", "a3+3"], function(a){
    return a.split("+")[0];
}, function(a){
    return a.split("+")[1]
});
//{a1: "1", a2: "2", a3: "3"}

//partitionReduce 
var partitionReduce = (function(){
    return function(ary, check) {
        return ary.reduce(function(prev, cur, index, array){
            prev[check(cur) ? 0 : 1].push(cur);
            return prev;
        }, [[], []]);
    }
})();
var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
partitionReduce(ary, function(n){
    return n % 2 == 0;
});
//[[2, 4, 6, 8, 10],[1, 3, 5, 7, 9]]

//pickFilter 
var pickFilter = (function(){
    return function(obj, ary){
        return ary.reduce(function(prev, cur, index, array){
            if(obj.hasOwnProperty(cur)){
                prev[cur] = obj[cur];
            }
            return prev;
        }, {});
    }
})();
pickFilter({ a: 1, b: '2', c: 3 }, ['a', 'b']); // {a: 1, b: "2"}
lynxerzhang commented 6 years ago
//array filter
var rejectFilter = (function(){
    return function(check, ary) {
        return ary.filter(function(item, index){
            return !check(item);
        });
    }
})();