enum.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * 枚举类
  3. * Enum.IMAGE.name => "图片"
  4. * Enum.getNameByKey('IMAGE') => "图片"
  5. * Enum.getValueByKey('IMAGE') => 10
  6. * Enum.getNameByValue(10) => "图片"
  7. * Enum.getData() => [{key: "IMAGE", name: "图片", value: 10}]
  8. */
  9. class Enum {
  10. constructor (param) {
  11. const keyArr = []
  12. const valueArr = []
  13. if (!Array.isArray(param)) {
  14. throw new Error('param is not an array!')
  15. }
  16. param.map(element => {
  17. if (!element.key || !element.name) {
  18. return
  19. }
  20. // 保存key值组成的数组,方便A.getName(name)类型的调用
  21. keyArr.push(element.key)
  22. valueArr.push(element.value)
  23. // 根据key生成不同属性值,以便A.B.name类型的调用
  24. this[element.key] = element
  25. if (element.key !== element.value) {
  26. this[element.value] = element
  27. }
  28. })
  29. // 保存源数组
  30. this.data = param
  31. this.keyArr = keyArr
  32. this.valueArr = valueArr
  33. // 防止被修改
  34. // Object.freeze(this)
  35. }
  36. // 根据key得到对象
  37. keyOf (key) {
  38. return this.data[this.keyArr.indexOf(key)]
  39. }
  40. // 根据key得到对象
  41. valueOf (key) {
  42. return this.data[this.valueArr.indexOf(key)]
  43. }
  44. // 根据key获取name值
  45. getNameByKey (key) {
  46. const prop = this.keyOf(key)
  47. if (!prop) {
  48. throw new Error('No enum constant' + key)
  49. }
  50. return prop.name
  51. }
  52. // 根据value获取name值
  53. getNameByValue (value) {
  54. const prop = this.valueOf(value)
  55. if (!prop) {
  56. throw new Error('No enum constant' + value)
  57. }
  58. return prop.name
  59. }
  60. // 根据key获取value值
  61. getValueByKey (key) {
  62. const prop = this.keyOf(key)
  63. if (!prop) {
  64. throw new Error('No enum constant' + key)
  65. }
  66. return prop.key
  67. }
  68. // 返回源数组
  69. getData () {
  70. return this.data
  71. }
  72. }
  73. export default Enum