@zk-tech/bedrock 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/dist/async/index.cjs.map +1 -1
  2. package/dist/async/index.d.cts +2 -2
  3. package/dist/async/index.d.ts +2 -2
  4. package/dist/async/index.js.map +1 -1
  5. package/dist/error/index.cjs.map +1 -1
  6. package/dist/error/index.d.cts +19 -19
  7. package/dist/error/index.d.ts +19 -19
  8. package/dist/error/index.js.map +1 -1
  9. package/dist/{error-base-B4zaiJ5m.d.cts → error-base-DOFtBFla.d.cts} +8 -8
  10. package/dist/{error-base-B4zaiJ5m.d.ts → error-base-DOFtBFla.d.ts} +8 -8
  11. package/dist/promise/index.cjs.map +1 -1
  12. package/dist/promise/index.d.cts +4 -4
  13. package/dist/promise/index.d.ts +4 -4
  14. package/dist/promise/index.js.map +1 -1
  15. package/dist/worker/index.cjs.map +1 -1
  16. package/dist/worker/index.d.cts +2 -2
  17. package/dist/worker/index.d.ts +2 -2
  18. package/dist/worker/index.js.map +1 -1
  19. package/package.json +1 -2
  20. package/src/_internal/logger.ts +0 -59
  21. package/src/array/array.test.ts +0 -35
  22. package/src/array/array.ts +0 -25
  23. package/src/array/index.ts +0 -1
  24. package/src/assert/assert.test.ts +0 -86
  25. package/src/assert/assert.ts +0 -42
  26. package/src/assert/index.ts +0 -2
  27. package/src/async/barrier.test.ts +0 -90
  28. package/src/async/barrier.ts +0 -58
  29. package/src/async/cancellation.test.ts +0 -85
  30. package/src/async/cancellation.ts +0 -193
  31. package/src/async/index.ts +0 -18
  32. package/src/async/queue/queue.test.ts +0 -70
  33. package/src/async/queue/queue.ts +0 -56
  34. package/src/async/queue/task.test.ts +0 -155
  35. package/src/async/queue/task.ts +0 -67
  36. package/src/async/utils.test.ts +0 -28
  37. package/src/async/utils.ts +0 -8
  38. package/src/async/wait.ts +0 -9
  39. package/src/byte/format.test.ts +0 -64
  40. package/src/byte/format.ts +0 -44
  41. package/src/byte/index.ts +0 -2
  42. package/src/byte/node_modules/.vitest/results.json +0 -1
  43. package/src/byte/var.ts +0 -11
  44. package/src/cache/index.ts +0 -2
  45. package/src/cache/lru-with-timeout.test.ts +0 -88
  46. package/src/cache/lru-with-timeout.ts +0 -85
  47. package/src/cache/lru.test.ts +0 -56
  48. package/src/cache/lru.ts +0 -59
  49. package/src/context/context.test.ts +0 -17
  50. package/src/context/context.ts +0 -60
  51. package/src/context/index.ts +0 -8
  52. package/src/di/base.ts +0 -73
  53. package/src/di/container-service.test.ts +0 -179
  54. package/src/di/context.web.tsx +0 -41
  55. package/src/di/descriptor.ts +0 -31
  56. package/src/di/idle-value.test.ts +0 -73
  57. package/src/di/idle-value.ts +0 -63
  58. package/src/di/index.common.ts +0 -32
  59. package/src/di/index.ts +0 -2
  60. package/src/di/instantiation-service.interface.ts +0 -46
  61. package/src/di/instantiation-service.test.ts +0 -337
  62. package/src/di/instantiation-service.ts +0 -468
  63. package/src/di/lazy/foo.mock.ts +0 -28
  64. package/src/di/lazy/idle-load.ts +0 -39
  65. package/src/di/lazy/index.ts +0 -4
  66. package/src/di/lazy/lazy-service.test.ts +0 -65
  67. package/src/di/lazy/lazy-service.ts +0 -71
  68. package/src/di/lazy/type.ts +0 -5
  69. package/src/di/node_modules/.vitest/results.json +0 -1
  70. package/src/di/proxy-builder.test.ts +0 -45
  71. package/src/di/proxy-builder.ts +0 -38
  72. package/src/di/service-collection.test.ts +0 -27
  73. package/src/di/service-collection.ts +0 -46
  74. package/src/di/service-ownership-collection.test.ts +0 -39
  75. package/src/di/service-ownership-collection.ts +0 -38
  76. package/src/di/service-registry.test.ts +0 -66
  77. package/src/di/service-registry.ts +0 -99
  78. package/src/di/trace.ts +0 -85
  79. package/src/dispose/disposable-store.test.ts +0 -57
  80. package/src/dispose/disposable-store.ts +0 -80
  81. package/src/dispose/disposable-t.test.ts +0 -123
  82. package/src/dispose/disposable-t.ts +0 -238
  83. package/src/dispose/disposable-utils.test.ts +0 -15
  84. package/src/dispose/disposable-utils.ts +0 -28
  85. package/src/dispose/dispose-base.ts +0 -9
  86. package/src/dispose/index.ts +0 -34
  87. package/src/dispose/logger.test.ts +0 -65
  88. package/src/dispose/logger.ts +0 -39
  89. package/src/dispose/timer.test.ts +0 -30
  90. package/src/dispose/timer.ts +0 -16
  91. package/src/dispose/tracker.test.ts +0 -51
  92. package/src/dispose/tracker.ts +0 -105
  93. package/src/error/error-base.ts +0 -45
  94. package/src/error/error-code.ts +0 -39
  95. package/src/error/error-const.test.ts +0 -30
  96. package/src/error/error-const.ts +0 -16
  97. package/src/error/error-or.test.ts +0 -44
  98. package/src/error/error-or.ts +0 -2
  99. package/src/error/error-t.test.ts +0 -116
  100. package/src/error/error-t.ts +0 -100
  101. package/src/error/index.ts +0 -24
  102. package/src/error/node_modules/.vitest/results.json +0 -1
  103. package/src/event/disposable-linked-list.ts +0 -29
  104. package/src/event/emitter.test.ts +0 -191
  105. package/src/event/emitter.ts +0 -162
  106. package/src/event/error-handler.ts +0 -22
  107. package/src/event/index.ts +0 -34
  108. package/src/event/once.ts +0 -29
  109. package/src/event/phase-emitter.test.ts +0 -212
  110. package/src/event/phase-emitter.ts +0 -209
  111. package/src/event/shortcut-event-utils.ts +0 -33
  112. package/src/event/utils.ts +0 -6
  113. package/src/event/when.ts +0 -40
  114. package/src/function/debounce.test.ts +0 -274
  115. package/src/function/debounce.ts +0 -168
  116. package/src/function/index.ts +0 -2
  117. package/src/function/node_modules/.vitest/results.json +0 -1
  118. package/src/function/throttle.test.ts +0 -179
  119. package/src/function/throttle.ts +0 -26
  120. package/src/hash/hash-t.test.ts +0 -100
  121. package/src/hash/hash-t.ts +0 -51
  122. package/src/hash/index.ts +0 -3
  123. package/src/json/index.ts +0 -1
  124. package/src/json/node_modules/.vitest/results.json +0 -1
  125. package/src/json/parse.ts +0 -19
  126. package/src/launch/abstract-job.ts +0 -45
  127. package/src/launch/cost-recorder.ts +0 -22
  128. package/src/launch/index.ts +0 -2
  129. package/src/launch/job-scheduler.test.ts +0 -122
  130. package/src/launch/job-scheduler.ts +0 -118
  131. package/src/launch/node_modules/.vitest/deps/_metadata.json +0 -8
  132. package/src/launch/node_modules/.vitest/deps/package.json +0 -3
  133. package/src/launch/node_modules/.vitest/results.json +0 -1
  134. package/src/lock/README.md +0 -11
  135. package/src/lock/capability.test.ts +0 -110
  136. package/src/lock/capability.ts +0 -89
  137. package/src/lock/index.ts +0 -15
  138. package/src/lock/node_modules/.vitest/results.json +0 -1
  139. package/src/lock/semaphore.ts +0 -21
  140. package/src/lock/shared-mutex.test.ts +0 -537
  141. package/src/lock/shared-mutex.ts +0 -242
  142. package/src/lock/utils.test.ts +0 -165
  143. package/src/lock/utils.ts +0 -135
  144. package/src/lodash-es/index.ts +0 -1
  145. package/src/math/degree.ts +0 -16
  146. package/src/math/index.ts +0 -7
  147. package/src/math/math.test.ts +0 -40
  148. package/src/math/math.ts +0 -64
  149. package/src/math/node_modules/.vitest/results.json +0 -1
  150. package/src/math/vector.test.ts +0 -73
  151. package/src/math/vector.ts +0 -114
  152. package/src/network/client.interface.ts +0 -104
  153. package/src/network/client.web.ts +0 -24
  154. package/src/network/index.common.ts +0 -10
  155. package/src/network/index.ts +0 -2
  156. package/src/network/plugins/retry.ts +0 -98
  157. package/src/objects/deep-clone.test.ts +0 -40
  158. package/src/objects/deep-clone.ts +0 -13
  159. package/src/objects/deep-equal.test.ts +0 -86
  160. package/src/objects/deep-equal.ts +0 -60
  161. package/src/objects/index.ts +0 -4
  162. package/src/platform/index.ts +0 -64
  163. package/src/promise/index.ts +0 -16
  164. package/src/promise/promise.test.ts +0 -254
  165. package/src/promise/promise.ts +0 -212
  166. package/src/scheduler/callback-token.ts +0 -31
  167. package/src/scheduler/core/actuator-args.test.ts +0 -47
  168. package/src/scheduler/core/actuator.test.ts +0 -82
  169. package/src/scheduler/core/actuator.ts +0 -58
  170. package/src/scheduler/core/chunk-scheduler.test.ts +0 -54
  171. package/src/scheduler/core/chunk-scheduler.ts +0 -28
  172. package/src/scheduler/core/node_modules/.vitest/results.json +0 -1
  173. package/src/scheduler/core/scheduler.test.ts +0 -328
  174. package/src/scheduler/core/scheduler.ts +0 -172
  175. package/src/scheduler/core/task-queue.test.ts +0 -78
  176. package/src/scheduler/core/task-queue.ts +0 -44
  177. package/src/scheduler/core/task.test.ts +0 -34
  178. package/src/scheduler/core/task.ts +0 -52
  179. package/src/scheduler/core/utils.ts +0 -48
  180. package/src/scheduler/executor/abstract-executor.test.ts +0 -44
  181. package/src/scheduler/executor/abstract-executor.ts +0 -38
  182. package/src/scheduler/executor/executor.interface.ts +0 -39
  183. package/src/scheduler/executor/idle-callback-executor.test.ts +0 -70
  184. package/src/scheduler/executor/idle-callback-executor.ts +0 -98
  185. package/src/scheduler/executor/make-executor.ts +0 -18
  186. package/src/scheduler/executor/post-message-executor.test.ts +0 -66
  187. package/src/scheduler/executor/post-message-executor.ts +0 -52
  188. package/src/scheduler/index.ts +0 -15
  189. package/src/scheduler/lv-scheduler-callback.ts +0 -19
  190. package/src/scheduler/lv-scheduler-config.ts +0 -17
  191. package/src/scheduler/type.ts +0 -48
  192. package/src/sprintf/index.ts +0 -2
  193. package/src/sprintf/sprintf.test.ts +0 -95
  194. package/src/sprintf/sprintf.ts +0 -97
  195. package/src/structure/graph.test.ts +0 -181
  196. package/src/structure/graph.ts +0 -105
  197. package/src/structure/index.ts +0 -8
  198. package/src/structure/linked-list.test.ts +0 -74
  199. package/src/structure/linked-list.ts +0 -145
  200. package/src/structure/min-heap.test.ts +0 -71
  201. package/src/structure/min-heap.ts +0 -91
  202. package/src/type/REAME.md +0 -2
  203. package/src/type/distributive-omit.interface.ts +0 -4
  204. package/src/type/index.ts +0 -3
  205. package/src/type/object-key-paths.interface.ts +0 -40
  206. package/src/undo-redo-stack/README.md +0 -61
  207. package/src/undo-redo-stack/action-stack.test.ts +0 -330
  208. package/src/undo-redo-stack/action-stack.ts +0 -150
  209. package/src/undo-redo-stack/element.ts +0 -4
  210. package/src/undo-redo-stack/index.ts +0 -7
  211. package/src/undo-redo-stack/state-stack.test.ts +0 -118
  212. package/src/undo-redo-stack/state-stack.ts +0 -133
  213. package/src/uuid/index.ts +0 -7
  214. package/src/uuid/uuid.ts +0 -86
  215. package/src/worker/cors-worker.ts +0 -38
  216. package/src/worker/index.ts +0 -4
  217. package/src/worker/node_modules/.vitest/results.json +0 -1
  218. package/src/worker/promise-worker-main-thread.test.ts +0 -91
  219. package/src/worker/promise-worker-main-thread.ts +0 -76
  220. package/src/worker/promise-worker-worker-thread.ts +0 -64
  221. package/src/worker/promise-worker.interface.ts +0 -15
@@ -1,155 +0,0 @@
1
- /* eslint-disable prefer-promise-reject-errors */
2
- /* eslint-disable max-lines-per-function */
3
- import { CancellationTokenSource } from '../cancellation';
4
- import { AsyncTask } from './task';
5
-
6
- describe('AsyncTask', () => {
7
- test('resolve', async () => {
8
- const callback = vi.fn();
9
- const successCb = vi.fn();
10
- const failureCb = vi.fn();
11
- const cancelCb = vi.fn();
12
- const task1 = new AsyncTask(() => {
13
- callback();
14
- return Promise.resolve();
15
- });
16
- task1.onSuccess(successCb);
17
- task1.onFailure(failureCb);
18
- task1.onCancel(cancelCb);
19
-
20
- const result1 = await task1.safeExec();
21
- expect(callback).toHaveBeenCalled();
22
- expect(successCb).toHaveBeenCalled();
23
- expect(failureCb).not.toHaveBeenCalled();
24
- expect(cancelCb).not.toHaveBeenCalled();
25
- expect(result1).toBe(undefined);
26
- });
27
-
28
- test('reject', async () => {
29
- const callback = vi.fn();
30
- const successCb = vi.fn();
31
- const failureCb = vi.fn();
32
- const cancelCb = vi.fn();
33
- const error = new Error('error');
34
- const rej = Promise.reject(error);
35
- const task1 = new AsyncTask(() => {
36
- callback();
37
- return rej;
38
- });
39
- task1.onSuccess(successCb);
40
- task1.onFailure(failureCb);
41
- task1.onCancel(cancelCb);
42
-
43
- const result1 = await task1.safeExec();
44
- expect(callback).toHaveBeenCalled();
45
- expect(successCb).not.toHaveBeenCalled();
46
- expect(failureCb).toHaveBeenCalled();
47
- expect(cancelCb).not.toHaveBeenCalled();
48
- expect(result1).toBe(undefined);
49
- });
50
-
51
- test('cancel', async () => {
52
- const callback = vi.fn();
53
- const successCb = vi.fn();
54
- const failureCb = vi.fn();
55
- const cancelCb = vi.fn();
56
-
57
- const task1 = new AsyncTask(() => {
58
- callback();
59
- return Promise.reject();
60
- });
61
- task1.onSuccess(successCb);
62
- task1.onFailure(failureCb);
63
- task1.onCancel(cancelCb);
64
-
65
- task1.cancel();
66
- await task1.safeExec();
67
- expect(callback).not.toHaveBeenCalled();
68
- expect(successCb).not.toHaveBeenCalled();
69
- expect(failureCb).not.toHaveBeenCalled();
70
- expect(cancelCb).toHaveBeenCalled();
71
- });
72
-
73
- test('cancel 2', async () => {
74
- const callback = vi.fn();
75
- const successCb = vi.fn();
76
- const failureCb = vi.fn();
77
- const cancelCb = vi.fn();
78
-
79
- const task1 = new AsyncTask(() => {
80
- callback();
81
- return Promise.reject();
82
- });
83
- task1.onSuccess(successCb);
84
- task1.onFailure(failureCb);
85
- task1.onCancel(cancelCb);
86
-
87
- await task1.safeExec();
88
- task1.cancel();
89
- expect(callback).toHaveBeenCalled();
90
- expect(successCb).not.toHaveBeenCalled();
91
- expect(failureCb).toHaveBeenCalled();
92
- expect(cancelCb).not.toHaveBeenCalled();
93
- });
94
-
95
- /**
96
- * Testing the behaviors of aborting with abort signal
97
- * */
98
- test('aborts a task before it is exected should prevent task from being executed', async () => {
99
- const callback = vi.fn();
100
- const successCb = vi.fn();
101
- const failureCb = vi.fn();
102
- const cancelCb = vi.fn();
103
-
104
- const cancellationSource = new CancellationTokenSource();
105
-
106
- const task1 = new AsyncTask(() => {
107
- callback();
108
- return Promise.reject();
109
- }, cancellationSource.token);
110
-
111
- task1.onSuccess(successCb);
112
- task1.onFailure(failureCb);
113
- task1.onCancel(cancelCb);
114
-
115
- // aborts the task before it is executed
116
- cancellationSource.cancel();
117
- // The abort event of abort controller will be dispatched synchronously
118
-
119
- await task1.safeExec();
120
-
121
- expect(callback).not.toHaveBeenCalled();
122
- expect(successCb).not.toHaveBeenCalled();
123
- expect(failureCb).not.toHaveBeenCalled();
124
-
125
- expect(cancelCb).toHaveBeenCalled();
126
- });
127
-
128
- test('aborts a task after it has been executed should not cause the task to enter the cancelled stage', async () => {
129
- const callback = vi.fn();
130
- const successCb = vi.fn();
131
- const failureCb = vi.fn();
132
- const cancelCb = vi.fn();
133
-
134
- const cancellationSource = new CancellationTokenSource();
135
-
136
- const task1 = new AsyncTask(() => {
137
- callback();
138
- return Promise.reject();
139
- }, cancellationSource.token);
140
- task1.onSuccess(successCb);
141
- task1.onFailure(failureCb);
142
- task1.onCancel(cancelCb);
143
-
144
- await task1.safeExec();
145
-
146
- // aborts the task after it has been executed
147
- cancellationSource.cancel();
148
-
149
- expect(callback).toHaveBeenCalled();
150
- expect(successCb).not.toHaveBeenCalled();
151
- expect(failureCb).toHaveBeenCalled();
152
-
153
- expect(cancelCb).not.toHaveBeenCalled();
154
- });
155
- });
@@ -1,67 +0,0 @@
1
- import { Disposable, type IDisposable } from '@/dispose';
2
- import { type Event, Emitter } from '@/event';
3
- import { makeErrorBy, type ILvErrorRef } from '@/error';
4
- import { CancellationToken, type ICancellationToken } from '../cancellation';
5
-
6
- export interface IAsyncTask extends IDisposable {
7
- onSuccess: Event<[]>;
8
- onFailure: Event<[ILvErrorRef]>;
9
- onCancel: Event<[]>;
10
-
11
- /** 取消当前任务 */
12
- cancel: () => void;
13
- }
14
-
15
- export class AsyncTask extends Disposable implements IAsyncTask {
16
- private readonly _onSuccess = this._store.add(new Emitter<[]>());
17
- public readonly onSuccess = this._onSuccess.event;
18
-
19
- private readonly _onFailure = this._store.add(new Emitter<[ILvErrorRef]>());
20
- public readonly onFailure = this._onFailure.event;
21
-
22
- private readonly _onCancel = this._store.add(new Emitter<[]>());
23
- public readonly onCancel = this._onCancel.event;
24
-
25
- private _isExec: boolean = false;
26
- private _isCancel: boolean = false;
27
-
28
- constructor(
29
- private _callback: ((cancellation: ICancellationToken) => Promise<void>) | null,
30
- private readonly _cancellationToken?: ICancellationToken,
31
- ) {
32
- super();
33
-
34
- this._cancellationToken?.onCancellationRequested(() => {
35
- this.cancel();
36
- });
37
- }
38
-
39
- /** 这个方法不对外暴露,只提供给 queue 使用. */
40
- async safeExec(): Promise<void> {
41
- if (this._isCancel || this._isExec) {
42
- return;
43
- }
44
-
45
- try {
46
- this._isExec = true;
47
- await this._callback!(this._cancellationToken ?? CancellationToken.None);
48
- this._onSuccess.fire();
49
- } catch (err) {
50
- /** handler error */
51
- this._onFailure.fire(makeErrorBy(-1, 'exec error', err as Error));
52
- }
53
- }
54
-
55
- cancel(): void {
56
- if (this._isCancel) {
57
- return;
58
- }
59
- if (this._isExec) {
60
- return;
61
- }
62
-
63
- this._isCancel = true;
64
- this._callback = null;
65
- this._onCancel.fire();
66
- }
67
- }
@@ -1,28 +0,0 @@
1
- import { invokeNextLoop } from './utils';
2
-
3
- describe('invokeNextLoop', () => {
4
- beforeEach(() => {
5
- vi.useFakeTimers();
6
- });
7
-
8
- it('invoke', () => {
9
- let a = 0;
10
- invokeNextLoop(() => {
11
- a++;
12
- });
13
- expect(a).toBe(0);
14
- vi.advanceTimersByTime(1);
15
- expect(a).toBe(1);
16
- });
17
-
18
- it('dispose', () => {
19
- let a = 0;
20
- const disposable = invokeNextLoop(() => {
21
- a++;
22
- });
23
- expect(a).toBe(0);
24
- disposable.dispose();
25
- vi.advanceTimersByTime(1);
26
- expect(a).toBe(0);
27
- });
28
- });
@@ -1,8 +0,0 @@
1
- import { makeSafeDisposable } from '@/dispose';
2
-
3
- export function invokeNextLoop(fn: (...args: any[]) => void) {
4
- const handle = setTimeout(() => {
5
- fn();
6
- }, 0);
7
- return makeSafeDisposable(() => clearTimeout(handle));
8
- }
package/src/async/wait.ts DELETED
@@ -1,9 +0,0 @@
1
- /**
2
- * 等待一段时间
3
- * @param ms 单位毫秒
4
- */
5
- export function wait(ms: number): Promise<undefined> {
6
- return new Promise((resolve) => setTimeout(resolve, ms));
7
- }
8
-
9
- export const sleep: (ms: number) => Promise<undefined> = wait;
@@ -1,64 +0,0 @@
1
- import { getDefaultFormat, byteSizeFormat } from './format';
2
-
3
- describe('getDefaultFormat', () => {
4
- it('should return b for values less than 0.1KB', () => {
5
- expect(getDefaultFormat(100)).toBe('b');
6
- });
7
-
8
- it('should return kb for values between 0.1KB and 0.1MB', () => {
9
- expect(getDefaultFormat(1024)).toBe('kb');
10
- expect(getDefaultFormat(10 * 1024)).toBe('kb');
11
- });
12
-
13
- it('should return mb for values between 0.1MB and 1GB', () => {
14
- expect(getDefaultFormat(1024 * 1024)).toBe('mb');
15
- expect(getDefaultFormat(100 * 1024 * 1024)).toBe('mb');
16
- });
17
-
18
- it('should return gb for values between 1GB and 1TB', () => {
19
- expect(getDefaultFormat(2 * 1024 * 1024 * 1024)).toBe('gb');
20
- });
21
-
22
- it('should return tb for values greater than 1TB', () => {
23
- expect(getDefaultFormat(2 * 1024 * 1024 * 1024 * 1024)).toBe('tb');
24
- });
25
- });
26
-
27
- describe('byteSizeFormat', () => {
28
- it('should format bytes correctly', () => {
29
- expect(byteSizeFormat(100, 'b')).toBe('100B');
30
- expect(byteSizeFormat(100.123, 'b')).toBe('100.12B');
31
- });
32
-
33
- it('should format kilobytes correctly', () => {
34
- expect(byteSizeFormat(1024, 'kb')).toBe('1KB');
35
- expect(byteSizeFormat(1536, 'kb')).toBe('1.50KB');
36
- });
37
-
38
- it('should format megabytes correctly', () => {
39
- expect(byteSizeFormat(1024 * 1024, 'mb')).toBe('1MB');
40
- expect(byteSizeFormat(1.5 * 1024 * 1024, 'mb')).toBe('1.50MB');
41
- });
42
-
43
- it('should format gigabytes correctly', () => {
44
- expect(byteSizeFormat(1024 * 1024 * 1024, 'gb')).toBe('1GB');
45
- expect(byteSizeFormat(2.5 * 1024 * 1024 * 1024, 'gb')).toBe('2.50GB');
46
- });
47
-
48
- it('should format terabytes correctly', () => {
49
- expect(byteSizeFormat(1024 * 1024 * 1024 * 1024, 'tb')).toBe('1TB');
50
- expect(byteSizeFormat(1.5 * 1024 * 1024 * 1024 * 1024, 'tb')).toBe('1.50TB');
51
- });
52
-
53
- it('should use default format when no format is specified', () => {
54
- expect(byteSizeFormat(100)).toBe('100B');
55
- expect(byteSizeFormat(1024 * 100)).toBe('100KB');
56
- expect(byteSizeFormat(1024 * 1024 * 100)).toBe('100MB');
57
- expect(byteSizeFormat(1024 * 1024 * 1024 * 2)).toBe('2GB');
58
- });
59
-
60
- it('should remove .00 from formatted values', () => {
61
- expect(byteSizeFormat(1024 * 1024, 'mb')).toBe('1MB');
62
- expect(byteSizeFormat(2000, 'b')).toBe('2000B');
63
- });
64
- });
@@ -1,44 +0,0 @@
1
- export function getDefaultFormat(value: number) {
2
- if (value < 0.1 * 1024) {
3
- // 小于0.1KB,则转化成B
4
- return 'b';
5
- }
6
- if (value < 0.1 * 1024 * 1024) {
7
- // 小于0.1MB,则转化成KB
8
- return 'kb';
9
- }
10
- if (value < 1 * 1024 * 1024 * 1024) {
11
- // 小于0.1GB,则转化成MB
12
- return 'mb';
13
- }
14
- if (value < 1 * 1024 * 1024 * 1024 * 1024) {
15
- // 其他转化成GB
16
- return 'gb';
17
- }
18
- return 'tb';
19
- }
20
-
21
- const formatMap = {
22
- b: (value: number) => `${value.toFixed(2)}B`,
23
- kb: (value: number) => `${(value / 1024).toFixed(2)}KB`,
24
- mb: (value: number) => `${(value / (1024 * 1024)).toFixed(2)}MB`,
25
- gb: (value: number) => `${(value / (1024 * 1024 * 1024)).toFixed(2)}GB`,
26
- tb: (value: number) => `${(value / (1024 * 1024 * 1024 * 1024)).toFixed(2)}TB`,
27
- };
28
-
29
- export function byteSizeFormat(limit: number, format?: 'b' | 'kb' | 'mb' | 'gb' | 'tb'): string {
30
- let size = '';
31
-
32
- const resetFormat = format || getDefaultFormat(limit);
33
-
34
- size = formatMap[resetFormat](limit);
35
-
36
- const sizeStr = `${size}`; // 转成字符串
37
- const index = sizeStr.indexOf('.'); // 获取小数点处的索引
38
- const dou = sizeStr.substr(index + 1, 2); // 获取小数点后两位的值
39
- if (dou === '00') {
40
- // 判断后两位是否为00,如果是则删除00
41
- return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
42
- }
43
- return size;
44
- }
package/src/byte/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './var';
2
- export { byteSizeFormat } from './format';
@@ -1 +0,0 @@
1
- {"version":"1.0.1","results":[[":format.test.ts",{"duration":2,"failed":false}]]}
package/src/byte/var.ts DELETED
@@ -1,11 +0,0 @@
1
- // 常用常量
2
- export const kb = 1024;
3
- export const mb = kb * 1024;
4
- export const gb = mb * 1024;
5
- export const tb = gb * 1024;
6
-
7
- // 常用常量支持大写
8
- export const KB = kb;
9
- export const MB = mb;
10
- export const GB = gb;
11
- export const TB = tb;
@@ -1,2 +0,0 @@
1
- export { LRUCache } from './lru';
2
- export { LRUCacheWithTimeout } from './lru-with-timeout';
@@ -1,88 +0,0 @@
1
- import { LRUCacheWithTimeout } from './lru-with-timeout';
2
-
3
- class Foo {
4
- constructor(public readonly value: string) {}
5
- }
6
-
7
- // LRU基本能力依然保留
8
- describe('LRU Base', () => {
9
- let cache: LRUCacheWithTimeout<Foo>;
10
-
11
- beforeEach(() => {
12
- // 创建一个容量为5的缓存实例
13
- cache = new LRUCacheWithTimeout<Foo>(5, 100);
14
-
15
- // 向缓存中添加一些初始数据供测试使用
16
- cache.put('1', new Foo('apple'));
17
- cache.put('2', new Foo('banana'));
18
- cache.put('3', new Foo('orange'));
19
- });
20
-
21
- it('should return the value when getting an existing key', () => {
22
- const result = cache.get('2');
23
- expect(result).not.toBeUndefined();
24
- expect(result!.value).toBe('banana');
25
- });
26
-
27
- it('should return undefined when getting a non-existing key', () => {
28
- const result = cache.get('4');
29
- expect(result).toBeUndefined();
30
- });
31
-
32
- it('should update the value when putting an existing key', () => {
33
- cache.put('2', new Foo('grapefruit'));
34
- const result = cache.get('2');
35
- expect(result).not.toBeUndefined();
36
- expect(result!.value).toBe('grapefruit');
37
- });
38
-
39
- it('should add the key-value pair to the cache when putting a new key', () => {
40
- cache.put('4', new Foo('kiwi'));
41
- const result = cache.get('4');
42
- expect(result).not.toBeUndefined();
43
- expect(result!.value).toBe('kiwi');
44
- });
45
-
46
- it('should remove the least recently used item when the cache is full and a new item is added', () => {
47
- cache.put('4', new Foo('kiwi'));
48
- cache.put('5', new Foo('pear'));
49
- cache.put('6', new Foo('mango'));
50
- // 检查最早添加的项是否被移除
51
- const result1 = cache.get('1');
52
- const result2 = cache.get('2');
53
- expect(result1).toBeUndefined();
54
- expect(result2).not.toBeUndefined();
55
- expect(result2!.value).toBe('banana');
56
- });
57
- });
58
-
59
- // 判断超时逻辑
60
- describe('Timeout', () => {
61
- beforeAll(() => {
62
- vi.useFakeTimers();
63
- });
64
-
65
- it('timeout', () => {
66
- const now = Date.now();
67
- const cache = new LRUCacheWithTimeout<Foo>(5, 200);
68
- cache.put('1', new Foo('capcut'));
69
- const result1 = cache.get('1');
70
- expect(result1).not.toBeUndefined();
71
-
72
- vi.spyOn(Date, 'now').mockImplementationOnce(() => {
73
- return now + 100;
74
- });
75
- vi.advanceTimersByTime(100);
76
-
77
- const result2 = cache.get('1');
78
- expect(result2).not.toBeUndefined();
79
-
80
- vi.spyOn(Date, 'now').mockImplementationOnce(() => {
81
- return now + 300;
82
- });
83
- vi.advanceTimersByTime(300);
84
-
85
- const result3 = cache.get('1');
86
- expect(result3).toBeUndefined();
87
- });
88
- });
@@ -1,85 +0,0 @@
1
- import { ignoreDispose } from '@/dispose';
2
- import { LRUCache } from './lru';
3
-
4
- export class LRUCacheWithTimeout<T, K = string> {
5
- private readonly _updateTime: Map<K, number> = new Map();
6
- private _timer?: NodeJS.Timeout;
7
- private readonly _lru: LRUCache<T, K>;
8
-
9
- constructor(
10
- capacity: number,
11
- private readonly _timeout: number,
12
- ) {
13
- this._lru = new LRUCache(capacity);
14
-
15
- ignoreDispose(
16
- this._lru.onEvicted((key: K) => {
17
- this._updateTime.delete(key);
18
- }),
19
- );
20
- }
21
-
22
- get(key: K): T | undefined {
23
- const result = this._lru.get(key);
24
- if (result) {
25
- this._updateTime.set(key, Date.now() + this._timeout);
26
- }
27
- return result;
28
- }
29
-
30
- put(key: K, value: T): void {
31
- this._startTimer();
32
- this._updateTime.set(key, Date.now() + this._timeout);
33
- return this._lru.put(key, value);
34
- }
35
-
36
- remove(key: K): void {
37
- this._updateTime.delete(key);
38
- return this._lru.remove(key);
39
- }
40
-
41
- size(): number {
42
- return this._lru.size();
43
- }
44
-
45
- clear(): void {
46
- this._updateTime.clear();
47
- return this._lru.clear();
48
- }
49
-
50
- dispose(): void {
51
- this.clear();
52
- clearTimeout(this._timer);
53
- }
54
-
55
- private _startTimer() {
56
- if (this._timer) {
57
- return;
58
- }
59
- this._timer = setTimeout(this._tick, this._timeout);
60
- }
61
-
62
- private _check() {
63
- const now = Date.now();
64
- const shouldRemove: K[] = [];
65
- for (const [key, time] of this._updateTime) {
66
- if (time <= now) {
67
- shouldRemove.push(key);
68
- }
69
- }
70
- for (const key of shouldRemove) {
71
- this._updateTime.delete(key);
72
- this._lru.remove(key);
73
- }
74
- }
75
-
76
- private readonly _tick = () => {
77
- this._check();
78
- if (this._lru.size() === 0) {
79
- // 不再轮询
80
- this._timer = undefined;
81
- return;
82
- }
83
- this._timer = setTimeout(this._tick, this._timeout);
84
- };
85
- }
@@ -1,56 +0,0 @@
1
- import { LRUCache } from './lru';
2
-
3
- class Foo {
4
- constructor(public readonly value: string) {}
5
- }
6
-
7
- describe('LRUCache', () => {
8
- let cache: LRUCache<Foo>;
9
-
10
- beforeEach(() => {
11
- // 创建一个容量为5的缓存实例
12
- cache = new LRUCache<Foo>(5);
13
-
14
- // 向缓存中添加一些初始数据供测试使用
15
- cache.put('1', new Foo('apple'));
16
- cache.put('2', new Foo('banana'));
17
- cache.put('3', new Foo('orange'));
18
- });
19
-
20
- it('should return the value when getting an existing key', () => {
21
- const result = cache.get('2');
22
- expect(result).not.toBeUndefined();
23
- expect(result!.value).toBe('banana');
24
- });
25
-
26
- it('should return undefined when getting a non-existing key', () => {
27
- const result = cache.get('4');
28
- expect(result).toBeUndefined();
29
- });
30
-
31
- it('should update the value when putting an existing key', () => {
32
- cache.put('2', new Foo('grapefruit'));
33
- const result = cache.get('2');
34
- expect(result).not.toBeUndefined();
35
- expect(result!.value).toBe('grapefruit');
36
- });
37
-
38
- it('should add the key-value pair to the cache when putting a new key', () => {
39
- cache.put('4', new Foo('kiwi'));
40
- const result = cache.get('4');
41
- expect(result).not.toBeUndefined();
42
- expect(result!.value).toBe('kiwi');
43
- });
44
-
45
- it('should remove the least recently used item when the cache is full and a new item is added', () => {
46
- cache.put('4', new Foo('kiwi'));
47
- cache.put('5', new Foo('pear'));
48
- cache.put('6', new Foo('mango'));
49
- // 检查最早添加的项是否被移除
50
- const result1 = cache.get('1');
51
- const result2 = cache.get('2');
52
- expect(result1).toBeUndefined();
53
- expect(result2).not.toBeUndefined();
54
- expect(result2!.value).toBe('banana');
55
- });
56
- });
package/src/cache/lru.ts DELETED
@@ -1,59 +0,0 @@
1
- import { Emitter, type Event } from '@/event';
2
-
3
- /**
4
- * LRUCache
5
- * T 是值类型
6
- * K 是索引类型,默认string
7
- */
8
- export class LRUCache<T, K = string> {
9
- protected readonly _cache: Map<K, T> = new Map();
10
- private _onEvicted?: Emitter<[K, T]>;
11
-
12
- constructor(private readonly _capacity: number) {}
13
-
14
- get onEvicted(): Event<[K, T]> {
15
- if (!this._onEvicted) {
16
- this._onEvicted = new Emitter();
17
- }
18
- return this._onEvicted.event;
19
- }
20
-
21
- get(key: K): T | undefined {
22
- const value = this._cache.get(key);
23
- if (value) {
24
- // 将访问过的 key 移到最近使用的位置
25
- this._cache.delete(key);
26
- this._cache.set(key, value);
27
- }
28
- return value;
29
- }
30
-
31
- put(key: K, value: T): void {
32
- if (this._cache.has(key)) {
33
- // 如果已存在该 key,则将其移动到最近使用的位置
34
- this._cache.delete(key);
35
- } else if (this._cache.size >= this._capacity) {
36
- // 如果已达到容量上限,则删除最久未使用的键值对
37
- const oldestKey = this._cache.keys().next().value as K;
38
- const oldestVal = this._onEvicted ? this._cache.get(oldestKey)! : null;
39
- this._cache.delete(oldestKey);
40
- this._onEvicted?.fire(oldestKey, oldestVal!);
41
- }
42
- this._cache.set(key, value);
43
- }
44
-
45
- remove(key: K): void {
46
- const obj = this._cache.get(key);
47
- if (obj) {
48
- this._cache.delete(key);
49
- }
50
- }
51
-
52
- size(): number {
53
- return this._cache.size;
54
- }
55
-
56
- clear(): void {
57
- this._cache.clear();
58
- }
59
- }