ConfigBase.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. cc.Class({
  2. name: 'ConfigBase',
  3. properties: {
  4. mainKey: "",
  5. indexsCache:null,
  6. multiple:[],
  7. multipleCache:null,
  8. table:null,
  9. tableName:"",
  10. isLoadFinish:false,
  11. },
  12. ctor() {
  13. },
  14. initTable(tableName, mainKey, multipleKey) {
  15. this.tableName = tableName;
  16. this.mainKey = mainKey;
  17. this.multiple = multipleKey;
  18. this.indexsCache = {};
  19. this.multipleCache = {};
  20. return this
  21. },
  22. setTable(table) {
  23. this.table = table
  24. },
  25. // 从主键中拿某一行数据
  26. getByMainKey(idx) {
  27. // 从缓存中拿数据
  28. let data = this.indexsCache[idx]
  29. if (data != undefined) {
  30. return data;
  31. }
  32. // 找数据
  33. for (let d of this.table) {
  34. if (d[this.mainKey] == idx) {
  35. data = d;
  36. break;
  37. }
  38. }
  39. // 缓存数据
  40. this.indexsCache[data[this.mainKey]] = data;
  41. return data;
  42. },
  43. // 从多主键中,拿数据
  44. getByMultipleKey() {
  45. // 参数跟多主键数量对应不上
  46. if (arguments.length != this.multiple.length) {
  47. if (arguments.length <= 0) {
  48. cc.log("multiple key is null");
  49. } else {
  50. cc.log("multiple key num not match curNum :" + arguments.length + " need num " + this.multiple.length);
  51. }
  52. return null;
  53. }
  54. // 从缓存中拿数据
  55. let curCache = this.findMultipleCache(arguments);
  56. if (curCache != null)
  57. {
  58. return curCache;
  59. }
  60. // 查找数据
  61. return this.getAndAddMultiple(arguments);
  62. },
  63. // 拿多主键数据并缓存
  64. getAndAddMultiple(args)
  65. {
  66. var result = [];
  67. // 结果拿出来
  68. for (let d of this.table)
  69. {
  70. let isMatch = true;
  71. for (let i = 0; i < this.multiple.length; i++) {
  72. const k = this.multiple[i];
  73. if (d[k] != args[i]) {
  74. isMatch = false;
  75. break
  76. }
  77. }
  78. if (isMatch)
  79. {
  80. result.push(d);
  81. }
  82. }
  83. // 添加到缓存区
  84. let curCache = this.multipleCache;
  85. for (let i = 0; i < args.length - 1; i++) {
  86. let k = args[i];
  87. let tmpCache = curCache[k];
  88. if (tmpCache == undefined)
  89. {
  90. curCache[k] = tmpCache = {}
  91. }
  92. curCache = tmpCache;
  93. }
  94. curCache[args[args.length - 1]] = result;
  95. return result;
  96. },
  97. // 从多主键缓存中拿数据
  98. findMultipleCache(args)
  99. {
  100. // 索引缓存
  101. let curCache = this.multipleCache;
  102. let isFindCache = true;
  103. for(let p of args) {
  104. if (curCache[p] == undefined) {
  105. isFindCache = false
  106. break
  107. }
  108. curCache = curCache[p]
  109. }
  110. if (isFindCache)
  111. {
  112. return curCache;
  113. }
  114. return null;
  115. },
  116. })