1
0

NPCAccessor.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. type NPC = NPCAccessor & {[key:string]:any};
  2. class NPCAccessor{
  3. static _getHandler = function(target, prop){
  4. if(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(target), prop)?.get){
  5. return target[prop];
  6. }
  7. if(typeof target[prop] === 'function')
  8. return new Proxy(target[prop], {
  9. apply: (functionName, thisArg, argumentsList) => Reflect.apply(functionName, target, argumentsList)
  10. });
  11. return target.get(prop);
  12. }
  13. static handler = {
  14. get(target, prop) {
  15. if(prop.endsWith('_possessive')){
  16. prop = prop.replace('_possessive','');
  17. let value = NPCAccessor._getHandler(target,prop);
  18. if(value.endsWith('s'))
  19. return value+"'"; //https://dictionary.cambridge.org/grammar/british-grammar/possession-john-s-car-a-friend-of-mine
  20. return value + "'s";
  21. }
  22. return NPCAccessor._getHandler(target,prop);
  23. },
  24. set(target, prop, value, receiver){
  25. //console.warn(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(target), prop));
  26. if(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(target), prop)?.set){
  27. target[prop] = value;
  28. return true;
  29. }
  30. target.set(prop,value);
  31. return true;
  32. }
  33. };
  34. constructor(npcId=undefined){
  35. if(npcId)
  36. this._npcID = npcId;
  37. }
  38. _npcID: string;
  39. get id(){return this._npcID;}
  40. get(key:string,def:any=undefined){
  41. const NPCs = State.variables.npcs;
  42. return NPCs.get(this._npcID,key,def);
  43. }
  44. set(key:string,v:any){
  45. const NPCs = State.variables.npcs;
  46. return NPCs.set(this._npcID,key,v);
  47. }
  48. _init(nPCsDict){
  49. Object.keys(nPCsDict).forEach(function (pn) {
  50. this[pn] = clone(nPCsDict[pn]);
  51. }, this);
  52. return this;
  53. }
  54. clone = function () {
  55. return (new setup.NPCAccessor())._init(this);
  56. };
  57. toJSON = function () {
  58. var ownData = {};
  59. Object.keys(this).forEach(function (pn) {
  60. if(typeof this[pn] !== "function")
  61. ownData[pn] = clone(this[pn]);
  62. }, this);
  63. return JSON.reviveWrapper('(new setup.NPCAccessor())._init($ReviveData$)', ownData);
  64. };
  65. }
  66. setup.NPCAccessor = NPCAccessor;