SafeNumber.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * 防内存调试变量数字类型
  3. */
  4. class SafeVarNumber {
  5. private cache: number = 0;
  6. private scale: number = 2;
  7. private map: Object = {};
  8. private idx: number = 0;
  9. constructor(num: number = 0) {
  10. this.value = num;
  11. }
  12. /**数值 */
  13. get value() {
  14. if (Math.abs(this.map[this.idx] * this.scale - this.cache) > 0.000001) {
  15. this.map[this.idx] = this.cache / this.scale;
  16. }
  17. return this.map[this.idx];
  18. }
  19. set value(num: number) {
  20. delete this.map[this.idx];
  21. this.idx = Math.floor(Math.random() * 256);
  22. this.map[this.idx] = num;
  23. this.scale = Math.floor(Math.random() * 2) + 2;
  24. this.cache = num * this.scale;
  25. }
  26. valueOf() {
  27. return this.value;
  28. }
  29. toString() {
  30. return this.value.toString();
  31. }
  32. clone() {
  33. return new SafeVarNumber(this.value);
  34. }
  35. }
  36. /**
  37. * 防内存调试常量数字类型
  38. */
  39. class SafeConstNumber {
  40. private cache: number = 0;
  41. private scale: number = 2;
  42. private map: Object = {};
  43. private idx: number = 0;
  44. constructor(num: number = 0) {
  45. this.idx = Math.floor(Math.random() * 256);
  46. this.map[this.idx] = num;
  47. this.scale = Math.floor(Math.random() * 2) + 2;
  48. this.cache = num * this.scale;
  49. }
  50. /**数值 */
  51. get value() {
  52. let num = this.map[this.idx];
  53. if (Math.abs(num * this.scale - this.cache) > 0.000001) {
  54. num = this.cache / this.scale;
  55. }
  56. delete this.map[this.idx];
  57. this.idx = Math.floor(Math.random() * 256);
  58. this.map[this.idx] = num;
  59. return this.map[this.idx];
  60. }
  61. valueOf() {
  62. return this.value;
  63. }
  64. toString() {
  65. return this.value.toString();
  66. }
  67. clone() {
  68. return new SafeConstNumber(this.value);
  69. }
  70. }
  71. export function get_new_safe_number(num:number):SafeVarNumber { return new SafeVarNumber(num);}
  72. export function get_new_safe_const_number(num:number):SafeConstNumber { return new SafeConstNumber(num);}