[英]JavaScript/TypeScript Array interface[] , group by type to send 1 of many functions
I have an array
of Question ( interface
) that I need to send to 1 of many functions based on Question type. 我有一个问题
array
( interface
),我需要根据问题类型将其发送到许多函数中的一个。 I think my series of if
statements is very ugly and am hoping there is a way of doing this that adheres to SOLID. 我认为我的一系列
if
语句非常丑陋,希望有一种遵循SOLID的方法。 I believe I am violating O (Open for extension, closed for modification). 我相信我违反了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>`;
}
Then, 然后,
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>`;
}
it is ugly. 这很丑。 How about building a map of functions?
如何构建功能图? Perhaps something like
也许像
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>`;
}
If the logic inside the template is too large, then it can be moved to a function, such as 如果模板内部的逻辑太大,则可以将其移至某个函数,例如
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) };
}
However, I would question the wisdom of generating such a large tree all at once. 但是,我会质疑一次生成这么大树的智慧。 When I use YO I prefer to generate small items, and insert them using
appendChild
. 当我使用YO时,我更喜欢生成小项目,并使用
appendChild
插入它们。 For example, 例如,
renderQuestionList(contents: Question[]): HTMLElement {
let div = yo`<div> </div>`;
contents.forEach(q => {
div.appendChild(renderQuestion(q));
});
return div;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.