stack-var.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { Container } from "../packages";
  2. type Var = { [key in string]: any };
  3. type Key = Container;
  4. const stackMap = new WeakMap<Key, Var[]>();
  5. const getStack = (key: Key) => {
  6. const stack = stackMap.get(key);
  7. return stack || null;
  8. };
  9. const getCurrentVar = (key: Key) => {
  10. const stack = getStack(key);
  11. if (stack) {
  12. return stack[stack.length - 1];
  13. } else {
  14. throw "当前 key 不存在变量桟";
  15. }
  16. };
  17. export const varMount = (key: Key) => {
  18. const stack = getStack(key);
  19. if (!stack) {
  20. stackMap.set(key, []);
  21. } else {
  22. throw "当前 key 已挂载变量";
  23. }
  24. };
  25. export const varPush = (key: Key, data: Var) => {
  26. const stack = getStack(key);
  27. if (stack) {
  28. stack.push(data);
  29. }
  30. };
  31. export const varPop = (key: Key) => {
  32. const stack = getStack(key);
  33. if (stack?.length) {
  34. stack.pop();
  35. }
  36. };
  37. export const varAdd = (key: Key, k: string, v: any) => {
  38. const current = getCurrentVar(key);
  39. if (k in current) {
  40. throw `${key}变量已存在${current}`;
  41. } else {
  42. current[k] = v;
  43. }
  44. };
  45. export const varSet = (key: Key, k: string, v: any) => {
  46. const current = getCurrentVar(key);
  47. if (k in current) {
  48. throw `${key}变量已存在${current}`;
  49. } else {
  50. current[k] = v;
  51. }
  52. };
  53. export const varDel = (key: Key, k: string) => {
  54. const current = getCurrentVar(key);
  55. if (!(k in current)) {
  56. throw `${key}变量不存在${current}`;
  57. } else {
  58. delete current[k];
  59. }
  60. };
  61. const keyStack: Key[] = [];
  62. export let currentVar: Var;
  63. export const useVar = (key: Key) => {
  64. keyStack.push(key);
  65. currentVar = getCurrentVar(keyStack[keyStack.length - 1]);
  66. return () => {
  67. keyStack.pop();
  68. if (keyStack.length) {
  69. currentVar = getCurrentVar(keyStack[keyStack.length - 1]);
  70. } else {
  71. currentVar = null;
  72. }
  73. };
  74. };