JavaScript/TypeScript Array interface[] , group by type 发送许多函数中的一个

JavaScript/TypeScript Array interface[] , group by type to send 1 of many functions

我有一个 array 个问题 (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>`;
}

如果模板里面的逻辑太大,那么可以移到函数中,比如

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

    renderQuestion(q):HTMLElement {
        if (q.type == 'passfailna') { return this.renderQuestionPassfailna(q) };
        if (q.type == 'yesno') { return this.renderQuestionYesno(q) };
        if (q.type == 'numeric') { return this.renderQustionNumeric(q) };
    }

但是,我会质疑一次生成这么大的树是否明智。当我使用 YO 时,我更喜欢生成小项目,并使用 appendChild 插入它们。例如,

renderQuestionList(contents: Question[]): HTMLElement {
    let div = yo`<div> </div>`;
    contents.forEach(q => {
         div.appendChild(renderQuestion(q));
    });
    return div;
}