表驱动编程重构代码

177 阅读1分钟

一 重构前

大量使用if else,且每种情况代码逻辑类似,可以考虑使用表驱动编程优化代码。

//根据this.position的不同,从而设置content的位置
const {contentWrapper,triggerButton}=this.$refs;
document.body.appendChild(contentWrapper);
const {left,top,width,height}=triggerButton.getBoundingClientRect();
if(this.position==='top'){
    contentWrapper.style.left=left+window.scrollX+'px';
    contentWrapper.style.top=top+window.scrollY+'px';
}else if(this.position==='bottom'){
    contentWrapper.style.left=left+window.scrollX+'px';
    contentWrapper.style.top=top+height+window.scrollY+'px';
}else if(this.position==='left'){
    const {height:height2}=contentWrapper.getBoundingClientRect();
    contentWrapper.style.left=left+window.scrollX+'px';
    contentWrapper.style.top=top+window.scrollY+(height-height2)/2+'px';
}else if(this.position==='right'){
    const {height:height2}=contentWrapper.getBoundingClientRect();
    contentWrapper.style.left=left+window.scrollX+width+'px';
    contentWrapper.style.top=top+window.scrollY+(height-height2)/2+'px';
}

二 优化后

将条件判断语句中不同的部分抽象成一个对象,从而简化代码。

const {contentWrapper, triggerButton} = this.$refs;
document.body.appendChild(contentWrapper);
const {left, top, width, height} = triggerButton.getBoundingClientRect();
const {height: height2} = contentWrapper.getBoundingClientRect();
let positions = {
    top: {
        left: left + window.scrollX,
        top: top + window.scrollY,
    },
    bottom: {
        left: left + window.scrollX,
        top: top + height + window.scrollY,
    },
    left: {
        left: left + window.scrollX,
        top: top + window.scrollY + (height - height2) / 2,
    },
    right: {
        left: left + window.scrollX + width,
        top: top + window.scrollY + (height - height2) / 2,
    }
};
contentWrapper.style.left = positions[this.position].left + 'px';
contentWrapper.style.top = positions[this.position].top + 'px';