cc.Class({ name: 'ConfigBase', properties: { mainKey: "", indexsCache:null, multiple:[], multipleCache:null, table:null, tableName:"", isLoadFinish:false, }, ctor() { }, initTable(tableName, mainKey, multipleKey) { this.tableName = tableName; this.mainKey = mainKey; this.multiple = multipleKey; this.indexsCache = {}; this.multipleCache = {}; return this }, setTable(table) { this.table = table }, // 从主键中拿某一行数据 getByMainKey(idx) { // 从缓存中拿数据 let data = this.indexsCache[idx] if (data != undefined) { return data; } // 找数据 for (let d of this.table) { if (d[this.mainKey] == idx) { data = d; break; } } // 缓存数据 if (data) { this.indexsCache[data[this.mainKey]] = data; } return data; }, // 从多主键中,拿数据 getByMultipleKey() { // 参数跟多主键数量对应不上 if (arguments.length != this.multiple.length) { if (arguments.length <= 0) { cc.log("multiple key is null"); } else { cc.log("multiple key num not match curNum :" + arguments.length + " need num " + this.multiple.length); } return null; } // 从缓存中拿数据 let curCache = this.findMultipleCache(arguments); if (curCache != null) { return curCache; } // 查找数据 return this.getAndAddMultiple(arguments); }, // 拿多主键数据并缓存 getAndAddMultiple(args) { var result = []; // 结果拿出来 for (let d of this.table) { let isMatch = true; for (let i = 0; i < this.multiple.length; i++) { const k = this.multiple[i]; if (d[k] != args[i]) { isMatch = false; break } } if (isMatch) { result.push(d); } } // 添加到缓存区 let curCache = this.multipleCache; for (let i = 0; i < args.length - 1; i++) { let k = args[i]; let tmpCache = curCache[k]; if (tmpCache == undefined) { curCache[k] = tmpCache = {} } curCache = tmpCache; } curCache[args[args.length - 1]] = result; return result; }, // 从多主键缓存中拿数据 findMultipleCache(args) { // 索引缓存 let curCache = this.multipleCache; let isFindCache = true; for(let p of args) { if (curCache[p] == undefined) { isFindCache = false break } curCache = curCache[p] } if (isFindCache) { return curCache; } return null; }, })