鍍金池/ 問(wèn)答/Java  網(wǎng)絡(luò)安全  HTML/ js設(shè)計(jì)模式問(wèn)題

js設(shè)計(jì)模式問(wèn)題

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'
  }
}

這個(gè)方法如何改寫(xiě)成維護(hù)性高寫(xiě)法,類似于策略模式?

回答
編輯回答
囍槑

擴(kuò)展的話只用修改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;
}
2018年8月29日 08:35
編輯回答
檸檬藍(lán)

直接返回組件實(shí)例就行了,沒(méi)有更多代碼的話也沒(méi)什么好優(yōu)化的點(diǎn)。

2017年9月20日 12:38
編輯回答
痞性
function isCharts (type) {
  return ['pie','bar','line'].includes(type) ? 'CHARTS' : false
}

function isText (type) {
  return ['normalText','multText'].includes(type) ? 'TEXT' : false
}

function isMedia (type) {
  return ['file','picture','music','video'].includes(type) ? 'MEDIA' : false
}

const typefun = [isCharts, isText, isMedia]

export const typeMarry = (type) => {
  for (let i = 0, len = typefun.length; i < len; i++) {
    let cur = typefun[i](type)
    if (cur) return cur
  }
}
2018年4月19日 16:36