Mike-Zhu / note

note
3 stars 1 forks source link

骚操作改写2 #5

Open Mike-Zhu opened 5 years ago

Mike-Zhu commented 5 years ago

原代码,这里不需要用递归而用了递归,可以被简化

function getLastIndex({ ind, value, options }) {
    if (ind === 0) {
        return 0
    }

    let lastVal = value[ind - 1].floorId;
    let lastIndex = options.map(o => o.floorId).indexOf(lastVal);//上一个value选择的是

    if (lastIndex == -1) {
        return getLastIndex({ ind: ind - 1, value, options });
    } else {
        return lastIndex;
    }
}

版本一(业务,易读版): 不关注业务本身,只是风格变化

function getLastIndex({ ind, value, options }) {
    let floorIdList = options.map(option => option.floorId)
    for (var i = ind; i > 0; i--) {
        let lastVal = value[i - 1].floorId;
        let lastIndex = floorIdList.indexOf(lastVal);//上一个value选择的是
        if (lastIndex >= 0) return lastIndex
    }
    return i
}

版本二(单纯解决问题) 找到value中的某个floorId, 满足: 1.index不大于ind-1 2.该floorId存在于options中的 3.该floorId是满足上述条件的value中的最后一个

得出这个floorId在options的位置 不存在则返回0

function getLastIndex({ ind, value, options }) {
    let floorIdList = options.map(option => option.floorId)
    let ret = 0
    value.map(val => val.floorId)
        .slice(0, ind)
        .reverse()
        .some(lastVal =>
            (ret = Math.max(floorIdList.indexOf(lastVal), ret)) > 0)

    return ret
}