javascript - 构造函数接受 (1) 字符串列表;(2) str 数组;(3) 地图
问题描述
我想以这样的方式扩展构造函数,即 Level 和 Color 的两行可以取消注释。也就是说,可以生成一个带有映射的枚举和一个带有列表的枚举(第二个是低优先级)。
我可以放弃工作(未注释)变体并只接受数组,然后检查元素是字符串还是对象,但这个解决方案不会像我正在寻找的那样小众(只要它存在.. .)。
class Enum {
constructor (...values) {
this.values = values;
// this.map = None;
}
check (value) {
//if (this.map) {
// return this.map.keys().indexOf(value) !== -1;
// } else {
return this.values.indexOf(value) !== -1;
// }
}
}
const enums = {
Size: new Enum('small', 'big', 'huge'),
// Level: new Enum({'1': {txt: 'h1'}, '2': {txt: 'h2'}, '3': {txt: 'h3'}}),
// Color: new Enum(['small', 'big', 'huge']),
};
export default enums;
解决方案
“多态”构造函数主要是一个坏主意,因为它们很难编程(正如你已经知道的那样),而且在代码中也更难追踪。相反,我建议对每种可能的参数类型使用专门的工厂函数。例子:
class Enum {
constructor(pairs) {
for (let [name, val] of pairs)
this[name] = val;
}
static from(names) {
return new this([...names.entries()].map(([k, v]) => [v, k]));
}
static of(...names) {
return this.from(names);
}
static fromObject(obj) {
return new this(Object.entries(obj));
}
}
const enums = {
Size: Enum.of('small', 'big', 'huge'),
Level: Enum.fromObject({'first': {txt: 'h1'}, 'second': {txt: 'h2'}, 'third': {txt: 'h3'}}),
Color: Enum.from(['red', 'orange', 'blue']),
Flags: new Enum([['read', 1], ['write', 2], ['execute', 4]])
};
console.log(enums.Size.huge)
console.log(enums.Color.orange)
console.log(enums.Level.third)
console.log(enums.Flags.execute)
推荐阅读
- scikit-learn - 连接 sklearn Pipeline 中不同步骤的特征
- javascript - NextJS:如何参数化函数以根据链接呈现特定内容?
- indexing - 如何优化压缩时间序列数据集的倒排索引
- jfrog - Flutter 的依赖
- python - 为什么 LightGBM 中的 R2 分数为零?
- c - 为什么 Keil 在为 STM32F407 定义全局变量时向我显示警告
- .net - F# MailboxProcessor 异步混乱的打印语句
- html - 关于缺少 CSS 规则的警告?
- python - 初学者 Python:如何在我的代码中修复此函数检查,以便它循环返回以允许玩家选择
- tableau-api - Tableau Ask Data 服务将无法启动并且无法找到日志文件位置