猿问

js设计模式问题

export const typeMarry = (type) => {

  const charts = ['pie','bar','line'],

        text = ['normalText','multText'],

        media = ['file','picture','music','video']

  if(charts.indexOf(type) !== -1) {

    return 'CHARTS'

  }

  if(text.indexOf(type) !== -1) {

    return 'TEXT'

  }

  if(media.indexOf(type) !== -1) {

    return 'MEDIA'

  }

}

这个方法如何改写成维护性高写法,类似于策略模式?

白猪掌柜的
浏览 358回答 3
3回答

MYYA

扩展的话只用修改types就行了const types = {  'CHARTS':['pie','bar','line'],  'TEXT':['normalText','multText'],  'MEDIA':['file','picture','music','video'],}export const typeMarry = (type) => {   for(var k in types)     if(types[k].includes(type))       return k;}

一只甜甜圈

function isCharts (type) {&nbsp; return ['pie','bar','line'].includes(type) ? 'CHARTS' : false}function isText (type) {&nbsp; return ['normalText','multText'].includes(type) ? 'TEXT' : false}function isMedia (type) {&nbsp; return ['file','picture','music','video'].includes(type) ? 'MEDIA' : false}const typefun = [isCharts, isText, isMedia]export const typeMarry = (type) => {&nbsp; for (let i = 0, len = typefun.length; i < len; i++) {&nbsp; &nbsp; let cur = typefun[i](type)&nbsp; &nbsp; if (cur) return cur&nbsp; }}

ibeautiful

直接返回组件实例就行了,没有更多代码的话也没什么好优化的点。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答