js设计模式问题

发布于 2022-09-07 16:15:22 字数 416 浏览 34 评论 0

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦巷 2022-09-14 16:15:22

扩展的话只用修改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;
}
海夕 2022-09-14 16:15:22
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
  }
}
蓝海似她心 2022-09-14 16:15:22

直接返回组件实例就行了,没有更多代码的话也没什么好优化的点。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文