JavaScript 前端数据字典DictClass封装
1 /** 2 * author: hubary 3 * options: 字典项 4 * strict: 启用value严格相等 5 */ 6 export default class DictClass { 7 strict = true; 8 cache = {}; 9 constructor(options, strict) { 10 Object.defineProperty(this, "options", { 11 get() { 12 return Array.isArray(options) ? options : []; 13 }, 14 }); 15 if (typeof strict === "boolean") { 16 this.strict = strict; 17 } 18 } 19 // 根据value获取对应的label 20 get(val, defaultVal) { 21 if (!this.cache.hasOwnProperty(val)) { 22 // console.log('no cache', val) 23 this._fromFor(val); 24 } 25 if (this.cache[val]) { 26 return this.cache[val].label; 27 } 28 return defaultVal; 29 } 30 get keys() { 31 return this.options.map((v) => v.value); 32 } 33 // 根据value获取所在item 34 getItem(val) { 35 if (!this.cache.hasOwnProperty(val)) { 36 this._fromFor(val); 37 } 38 return this.cache[val]; 39 } 40 _isFinded(val, value) { 41 // 严格相等 42 if (this.strict) { 43 return val === value; 44 } 45 return val == value; 46 } 47 _fromFor(val) { 48 let result = null; 49 for (let item of this.options) { 50 if (this._isFinded(val, item.value)) { 51 result = item; 52 break; 53 } 54 } 55 if (result) { 56 this.cache[val] = Object.freeze(result); 57 } 58 } 59 }
使用方法:
1 export const dict_matchType = new DictClass([ 2 { label: "精确匹配", value: "0" }, 3 { label: "包含匹配", value: "1" }, 4 { label: "大于匹配", value: "2" }, 5 { label: "大于等于匹配", value: "3" }, 6 { label: "小于匹配", value: "4" }, 7 { label: "小于等于匹配", value: "5" }, 8 { label: "不等于匹配", value: "6" }, 9 { label: "前缀匹配", value: "7" }, 10 { label: "后缀匹配", value: "8" }, 11 { label: "路径模糊匹配", value: "9" }, 12 ])