Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

直接上代码吧 都在代码里写清楚了
问题就是

如何把函数中 tabs.filter.forEach 这些几乎相同的逻辑 独立出来 之前学习了策略模式 但是想不到好的方案 请大佬指点一二

let tabs = [{index:0,name:'angelaBaby'},{index:1,'陈冠西'},{index:2,'李bingbing'},{index:3,'范特西'}]
let COMMAND_TYPE_LIST = {
    OTHER:'other',
    RIGHT:'right',
    SELF:'self',
}

/**
 * @desc 抽中的成员逻辑
 * @param {*} type:string  - 抽中的类型  
 * @param {*} randomIndex:number - 抽中的数组 index
 * @example 
 * 比如 type==='other' randomIndex=1 那么抽中的成员就是 0,2,3
 * 比如 type==='right' randomIndex=1 那么抽中的成员就是 2,3
 * 比如 type==='self' randomIndex=1 那么抽中的成员就是 1
 * @todo
 * 如何把 tabs.filter.forEach 这些几乎相同的逻辑 独立出来 之前学习了策略模式 但是想不到好的方案 请大佬指点一二
 */
function checkedPerson(type,randomIndex){
    if (type === COMMAND_TYPE_LIST.OTHER) {
        //抽中其他
        tabs
            .filter((item, index) => index !== randomIndex)
            .forEach((tab) => {
                //循环处理逻辑
            })
    } else if (type === COMMAND_TYPE_LIST.RIGHT) {
        //抽中右侧
        tabs
            .filter((item, index) => index > randomIndex)
            .forEach((tab) => {
                //循环处理逻辑
            })
    } else if (type === COMMAND_TYPE_LIST.SELF) {
        //抽中自身
        tabs
            .filter((item, index) => index === randomIndex)
            .forEach((tab) => {
                //循环处理逻辑
            })
    }
}
checkedPerson(COMMAND_TYPE_LIST.OTHER,2)//抽中的成员就是 0,1,3


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
525 views
Welcome To Ask or Share your Answers For Others

1 Answer

解耦最终操作放在外面,可用性更高点

function checkedPerson1(type,randomIndex) {
    const other = (randomIndex, index) => index !== randomIndex;
    const right = (randomIndex, index) => index > randomIndex;
    const self = (randomIndex, index) => index === randomIndex;
    const dict = {
        other,
        right,
        self
    }
    return tabs.filter((item, index) => dict[type](randomIndex, index));
}
checkedPerson1('other', 1).forEach(item => {
    console.log(item);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...