首页 > 解决方案 > 构造函数接受 (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;

标签: javascriptecmascript-6constructor

解决方案


“多态”构造函数主要是一个坏主意,因为它们很难编程(正如你已经知道的那样),而且在代码中也更难追踪。相反,我建议对每种可能的参数类型使用专门的工厂函数。例子:

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)


推荐阅读