自定义数组切分合并算法

228 阅读1分钟

@TOC

需求

实现一个方法,传入一个数组,一个下标,一个插入方式,一个新的数组。返回切分合并后的数组

实现

第一种

第一种是使用lodash写的

首先进行特殊情况判定:传入的是祖父穿

function(arr, index, newArr, type="after"){
    if (!_.isArray(arr)) return;
    let catArr;
    if(typeof newArr === "string") newArr = [newArr];
    if(newArr.length === 0) return false;
    const options = {
        "after":()=>_.chunk(arr, index+1),
        "before":()=>_.chunk(arr, index),
        "concat":()=>_.concat(catArr[0],newArr,_.tail(catArr)),
    };
    // index 超出范围判断
    if(index<0) index = 0;
    if(index === 0 && type === "before") index = 0;
    if(index>arr.length) index = arr.length;
    if(index === arr.length-1 && type === "after") index = arr.length;
    // 头添加
    if(index === 0){
        // console.log("头添加")
        arr.unshift(...newArr);
        return arr;
    }
    // 尾部添加
    if(index === arr.length){
        // console.log("尾部添加")
        arr.push(...newArr);
        return arr;
    }
    // 根据type不同 切割数组
    catArr = options[type]();
    // 拼接数组
    catArr = _.concat(catArr[0],newArr,..._.tail(catArr));
    return catArr;
};

第二种

function(arr, index, newArr, type = "after"){
    if (!_.isArray(arr)) return;
    let i = index + 1;
    if(type == "before") i = i-1;
    if (!_.isArray(newArr)) newArr = [newArr];
    arr.splice(i,0,...newArr);
};