JavaScript/TypeScript Array interface[] ,按类型分组以发送多个函数中的 1 个

标签 javascript arrays typescript prototype solid-principles

我有一个问题(接口(interface))的数组,我需要根据问题类型将其发送到许多函数之一。我认为我的一系列 if 语句非常丑陋,我希望有一种遵循 SOLID 的方法来做到这一点。我相信我违反了 O(开放扩展,关闭修改)。

renderQuestionList(contents: Question[]): HTMLElement {
    return yo`
        <div>${contents.map(q => {
            if (q.type == 'passfailna') { return this.renderQuestionPassfailna(q) };
            if (q.type == 'yesno') { return this.renderQuestionYesno(q) };
            if (q.type == 'numeric') { return this.renderQustionNumeric(q) };
        })}
        </div>`;
}

那么,

    renderQuestionPassfailna(q: Question): any {
        return yo`<div>Stuff</div>`;
    }
    renderQuestionYesno(q: Question): any {
         return yo`<div>Other Stuff</div>`;
    }
    renderQustionNumeric(q: Question): any {
         return yo`<div>I'm Helping!</div>`;
    }

最佳答案

太丑了。构建功能图怎么样?也许类似

constructor() {
   this.questions = {
      passfailna: q => this.renderQuestionPassfailna(q),
      yesno: q => this.renderQuestionYesno(q),
      numeric: q => return this.renderQustionNumeric(q)
   };
}

renderQuestionList(contents: Question[]): HTMLElement {
    return yo`<div>${contents.map(q => this.questions[q.type](q))}</div>`;
}

关于JavaScript/TypeScript Array interface[] ,按类型分组以发送多个函数中的 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026818/

相关文章:

javascript - for循环将点击功能添加到jQuery中的多个输入字段未按预期工作

javascript - 为什么图片数组总是空的?

arrays - 自定义TableView错误

javascript - 将 Json 对象转换为单个数组

arrays - 在 TypeScript 中,我如何访问数组的成员?

javascript - 如何为每列设置单独的柱形图颜色?

arrays - 使用其中包含空格的元素创建 Bash 数组

java - foreach 和 for 循环将重复记录复制到数组中

javascript - '[object 对象],[object 对象 ]' for pipe ' AsyncPipe'

javascript - 我可以在 PDF 中嵌入 JavaScript 计数器吗?