@fluidframework/core-utils 2.0.0-dev-rc.1.0.0.224419

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 (111) hide show
  1. package/.eslintrc.js +36 -0
  2. package/.mocharc.js +13 -0
  3. package/CHANGELOG.md +81 -0
  4. package/LICENSE +21 -0
  5. package/README.md +75 -0
  6. package/api-extractor-lint.json +4 -0
  7. package/api-extractor.json +4 -0
  8. package/api-report/core-utils.api.md +147 -0
  9. package/dist/assert.d.ts +17 -0
  10. package/dist/assert.d.ts.map +1 -0
  11. package/dist/assert.js +25 -0
  12. package/dist/assert.js.map +1 -0
  13. package/dist/compare.d.ts +16 -0
  14. package/dist/compare.d.ts.map +1 -0
  15. package/dist/compare.js +28 -0
  16. package/dist/compare.js.map +1 -0
  17. package/dist/core-utils-alpha.d.ts +191 -0
  18. package/dist/core-utils-beta.d.ts +41 -0
  19. package/dist/core-utils-public.d.ts +41 -0
  20. package/dist/core-utils-untrimmed.d.ts +414 -0
  21. package/dist/delay.d.ts +11 -0
  22. package/dist/delay.d.ts.map +1 -0
  23. package/dist/delay.js +15 -0
  24. package/dist/delay.js.map +1 -0
  25. package/dist/heap.d.ts +86 -0
  26. package/dist/heap.d.ts.map +1 -0
  27. package/dist/heap.js +144 -0
  28. package/dist/heap.js.map +1 -0
  29. package/dist/index.d.ts +14 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +30 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/lazy.d.ts +44 -0
  34. package/dist/lazy.d.ts.map +1 -0
  35. package/dist/lazy.js +84 -0
  36. package/dist/lazy.js.map +1 -0
  37. package/dist/promiseCache.d.ts +89 -0
  38. package/dist/promiseCache.d.ts.map +1 -0
  39. package/dist/promiseCache.js +148 -0
  40. package/dist/promiseCache.js.map +1 -0
  41. package/dist/promises.d.ts +38 -0
  42. package/dist/promises.d.ts.map +1 -0
  43. package/dist/promises.js +60 -0
  44. package/dist/promises.js.map +1 -0
  45. package/dist/timer.d.ts +115 -0
  46. package/dist/timer.d.ts.map +1 -0
  47. package/dist/timer.js +189 -0
  48. package/dist/timer.js.map +1 -0
  49. package/dist/tsdoc-metadata.json +11 -0
  50. package/dist/unreachable.d.ts +22 -0
  51. package/dist/unreachable.d.ts.map +1 -0
  52. package/dist/unreachable.js +28 -0
  53. package/dist/unreachable.js.map +1 -0
  54. package/lib/assert.d.ts +17 -0
  55. package/lib/assert.d.ts.map +1 -0
  56. package/lib/assert.js +25 -0
  57. package/lib/assert.js.map +1 -0
  58. package/lib/compare.d.ts +16 -0
  59. package/lib/compare.d.ts.map +1 -0
  60. package/lib/compare.js +28 -0
  61. package/lib/compare.js.map +1 -0
  62. package/lib/core-utils-alpha.d.ts +191 -0
  63. package/lib/core-utils-beta.d.ts +41 -0
  64. package/lib/core-utils-public.d.ts +41 -0
  65. package/lib/core-utils-untrimmed.d.ts +414 -0
  66. package/lib/delay.d.ts +11 -0
  67. package/lib/delay.d.ts.map +1 -0
  68. package/lib/delay.js +15 -0
  69. package/lib/delay.js.map +1 -0
  70. package/lib/heap.d.ts +86 -0
  71. package/lib/heap.d.ts.map +1 -0
  72. package/lib/heap.js +144 -0
  73. package/lib/heap.js.map +1 -0
  74. package/lib/index.d.ts +14 -0
  75. package/lib/index.d.ts.map +1 -0
  76. package/lib/index.js +30 -0
  77. package/lib/index.js.map +1 -0
  78. package/lib/lazy.d.ts +44 -0
  79. package/lib/lazy.d.ts.map +1 -0
  80. package/lib/lazy.js +84 -0
  81. package/lib/lazy.js.map +1 -0
  82. package/lib/promiseCache.d.ts +89 -0
  83. package/lib/promiseCache.d.ts.map +1 -0
  84. package/lib/promiseCache.js +148 -0
  85. package/lib/promiseCache.js.map +1 -0
  86. package/lib/promises.d.ts +38 -0
  87. package/lib/promises.d.ts.map +1 -0
  88. package/lib/promises.js +60 -0
  89. package/lib/promises.js.map +1 -0
  90. package/lib/timer.d.ts +115 -0
  91. package/lib/timer.d.ts.map +1 -0
  92. package/lib/timer.js +189 -0
  93. package/lib/timer.js.map +1 -0
  94. package/lib/unreachable.d.ts +22 -0
  95. package/lib/unreachable.d.ts.map +1 -0
  96. package/lib/unreachable.js +28 -0
  97. package/lib/unreachable.js.map +1 -0
  98. package/package.json +111 -0
  99. package/prettier.config.cjs +8 -0
  100. package/src/assert.ts +23 -0
  101. package/src/compare.ts +33 -0
  102. package/src/delay.ts +12 -0
  103. package/src/heap.ts +182 -0
  104. package/src/index.ts +21 -0
  105. package/src/lazy.ts +88 -0
  106. package/src/promiseCache.ts +205 -0
  107. package/src/promises.ts +63 -0
  108. package/src/timer.ts +289 -0
  109. package/src/unreachable.ts +24 -0
  110. package/tsconfig.esnext.json +6 -0
  111. package/tsconfig.json +12 -0
@@ -0,0 +1,414 @@
1
+ /**
2
+ * A browser friendly assert library.
3
+ * Use this instead of the 'assert' package, which has a big impact on bundle sizes.
4
+ * @param condition - The condition that should be true, if the condition is false an error will be thrown.
5
+ * Only use this API when `false` indicates a logic error in the problem and thus a bug that should be fixed.
6
+ * @param message - The message to include in the error when the condition does not hold.
7
+ * A number should not be specified manually: use a string.
8
+ * Before a release, policy-check should be run, which will convert any asserts still using strings to
9
+ * use numbered error codes instead.
10
+ * @alpha
11
+ */
12
+ export declare function assert(condition: boolean, message: string | number): asserts condition;
13
+
14
+ /**
15
+ * Compare two arrays. Returns true if their elements are equivalent and in the same order.
16
+ *
17
+ * @alpha
18
+ *
19
+ * @param left - The first array to compare
20
+ * @param right - The second array to compare
21
+ * @param comparator - The function used to check if two `T`s are equivalent.
22
+ * Defaults to `Object.is()` equality (a shallow compare where NaN = NaN and -0 ≠ 0)
23
+ */
24
+ export declare const compareArrays: <T>(left: readonly T[], right: readonly T[], comparator?: (leftItem: T, rightItem: T, index: number) => boolean) => boolean;
25
+
26
+ /**
27
+ * A deferred creates a promise and the ability to resolve or reject it
28
+ * @alpha
29
+ */
30
+ export declare class Deferred<T> {
31
+ private readonly p;
32
+ private res;
33
+ private rej;
34
+ private completed;
35
+ constructor();
36
+ /**
37
+ * Returns whether the underlying promise has been completed
38
+ */
39
+ get isCompleted(): boolean;
40
+ /**
41
+ * Retrieves the underlying promise for the deferred
42
+ *
43
+ * @returns the underlying promise
44
+ */
45
+ get promise(): Promise<T>;
46
+ /**
47
+ * Resolves the promise
48
+ *
49
+ * @param value - the value to resolve the promise with
50
+ */
51
+ resolve(value: T | PromiseLike<T>): void;
52
+ /**
53
+ * Rejects the promise
54
+ *
55
+ * @param value - the value to reject the promise with
56
+ */
57
+ reject(error: any): void;
58
+ }
59
+
60
+ /**
61
+ * Returns a promise that resolves after `timeMs`.
62
+ * @param timeMs - Time in milliseconds to wait.
63
+ * @internal
64
+ */
65
+ export declare const delay: (timeMs: number) => Promise<void>;
66
+
67
+ /**
68
+ * Ordered {@link https://en.wikipedia.org/wiki/Heap_(data_structure) | Heap} data structure implementation.
69
+ * @internal
70
+ */
71
+ export declare class Heap<T> {
72
+ comp: IComparer<T>;
73
+ private L;
74
+ /**
75
+ * Creates an instance of `Heap` with comparer.
76
+ * @param comp - A comparer that specify how elements are ordered.
77
+ */
78
+ constructor(comp: IComparer<T>);
79
+ /**
80
+ * Return the smallest element in the heap as determined by the order of the comparer
81
+ *
82
+ * @returns Heap node containing the smallest element
83
+ */
84
+ peek(): IHeapNode<T> | undefined;
85
+ /**
86
+ * Get and remove the smallest element in the heap as determined by the order of the comparer
87
+ *
88
+ * @returns The smallest value in the heap
89
+ */
90
+ get(): T | undefined;
91
+ /**
92
+ * Add a value to the heap
93
+ *
94
+ * @param x - value to add
95
+ * @returns The heap node that contains the value
96
+ */
97
+ add(x: T): IHeapNode<T>;
98
+ /**
99
+ * Allows for the Heap to be updated after a node's value changes.
100
+ */
101
+ update(node: IHeapNode<T>): void;
102
+ /**
103
+ * Removes the given node from the heap.
104
+ *
105
+ * @param node - The node to remove from the heap.
106
+ */
107
+ remove(node: IHeapNode<T>): void;
108
+ /**
109
+ * Get the number of elements in the Heap.
110
+ *
111
+ * @returns The number of elements in the Heap.
112
+ */
113
+ count(): number;
114
+ private fixup;
115
+ private isGreaterThanParent;
116
+ private fixdown;
117
+ private swap;
118
+ }
119
+
120
+ /**
121
+ * Interface for a comparer.
122
+ * @internal
123
+ */
124
+ export declare interface IComparer<T> {
125
+ /**
126
+ * The minimum value of type T.
127
+ */
128
+ min: T;
129
+ /**
130
+ * Compare the two value
131
+ *
132
+ * @returns 0 if the value is equal, negative number if a is smaller then b, positive number otherwise
133
+ */
134
+ compare(a: T, b: T): number;
135
+ }
136
+
137
+ /**
138
+ * Interface to a node in {@link Heap}.
139
+ * @internal
140
+ */
141
+ export declare interface IHeapNode<T> {
142
+ value: T;
143
+ position: number;
144
+ }
145
+
146
+ /**
147
+ * Timer which offers a promise that fulfills when the timer
148
+ * completes.
149
+ * @internal
150
+ */
151
+ export declare interface IPromiseTimer extends ITimer {
152
+ /**
153
+ * Starts the timer and returns a promise that
154
+ * resolves when the timer times out or is canceled.
155
+ */
156
+ start(): Promise<IPromiseTimerResult>;
157
+ }
158
+
159
+ /**
160
+ * @internal
161
+ */
162
+ export declare interface IPromiseTimerResult {
163
+ timerResult: "timeout" | "cancel";
164
+ }
165
+
166
+ /**
167
+ * @internal
168
+ */
169
+ export declare interface ITimer {
170
+ /**
171
+ * True if timer is currently running
172
+ */
173
+ readonly hasTimer: boolean;
174
+ /**
175
+ * Starts the timer
176
+ */
177
+ start(): void;
178
+ /**
179
+ * Cancels the timer if already running
180
+ */
181
+ clear(): void;
182
+ }
183
+
184
+ /**
185
+ * Helper class for lazy initialized values. Ensures the value is only generated once, and remain immutable.
186
+ * @internal
187
+ */
188
+ export declare class Lazy<T> {
189
+ private readonly valueGenerator;
190
+ private _value;
191
+ private _evaluated;
192
+ /**
193
+ * Instantiates an instance of Lazy<T>.
194
+ * @param valueGenerator - The function that will generate the value when value is accessed the first time.
195
+ */
196
+ constructor(valueGenerator: () => T);
197
+ /**
198
+ * Return true if the value as been generated, otherwise false.
199
+ */
200
+ get evaluated(): boolean;
201
+ /**
202
+ * Get the value. If this is the first call the value will be generated.
203
+ */
204
+ get value(): T;
205
+ }
206
+
207
+ /**
208
+ * A lazy evaluated promise. The execute function is delayed until
209
+ * the promise is used, e.g. await, then, catch ...
210
+ * The execute function is only called once.
211
+ * All calls are then proxied to the promise returned by the execute method.
212
+ * @alpha
213
+ */
214
+ export declare class LazyPromise<T> implements Promise<T> {
215
+ private readonly execute;
216
+ get [Symbol.toStringTag](): string;
217
+ private result;
218
+ constructor(execute: () => Promise<T>);
219
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
220
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined): Promise<T | TResult>;
221
+ finally(onfinally?: (() => void) | null | undefined): Promise<T>;
222
+ private getPromise;
223
+ }
224
+
225
+ /**
226
+ * A comparer for numbers.
227
+ * @internal
228
+ */
229
+ export declare const NumberComparer: IComparer<number>;
230
+
231
+ /**
232
+ * A specialized cache for async work, allowing you to safely cache the promised result of some async work
233
+ * without fear of running it multiple times or losing track of errors.
234
+ * @alpha
235
+ */
236
+ export declare class PromiseCache<TKey, TResult> {
237
+ private readonly cache;
238
+ private readonly gc;
239
+ private readonly removeOnError;
240
+ /**
241
+ * Create the PromiseCache with the given options, with the following defaults:
242
+ *
243
+ * expiry: indefinite, removeOnError: true for all errors
244
+ */
245
+ constructor({ expiry, removeOnError, }?: PromiseCacheOptions);
246
+ /**
247
+ * Check if there's anything cached at the given key
248
+ */
249
+ has(key: TKey): boolean;
250
+ /**
251
+ * Get the Promise for the given key, or undefined if it's not found.
252
+ * Extend expiry if applicable.
253
+ */
254
+ get(key: TKey): Promise<TResult> | undefined;
255
+ /**
256
+ * Remove the Promise for the given key, returning true if it was found and removed
257
+ */
258
+ remove(key: TKey): boolean;
259
+ /**
260
+ * Try to add the result of the given asyncFn, without overwriting an existing cache entry at that key.
261
+ * Returns a Promise for the added or existing async work being done at that key.
262
+ * @param key - key name where to store the async work
263
+ * @param asyncFn - the async work to do and store, if not already in progress under the given key
264
+ */
265
+ addOrGet(key: TKey, asyncFn: () => Promise<TResult>): Promise<TResult>;
266
+ /**
267
+ * Try to add the result of the given asyncFn, without overwriting an existing cache entry at that key.
268
+ * Returns false if the cache already contained an entry at that key, and true otherwise.
269
+ * @param key - key name where to store the async work
270
+ * @param asyncFn - the async work to do and store, if not already in progress under the given key
271
+ */
272
+ add(key: TKey, asyncFn: () => Promise<TResult>): boolean;
273
+ /**
274
+ * Try to add the given value, without overwriting an existing cache entry at that key.
275
+ * Returns a Promise for the added or existing async work being done at that key.
276
+ * @param key - key name where to store the async work
277
+ * @param value - value to store
278
+ */
279
+ addValueOrGet(key: TKey, value: TResult): Promise<TResult>;
280
+ /**
281
+ * Try to add the given value, without overwriting an existing cache entry at that key.
282
+ * Returns false if the cache already contained an entry at that key, and true otherwise.
283
+ * @param key - key name where to store the value
284
+ * @param value - value to store
285
+ */
286
+ addValue(key: TKey, value: TResult): boolean;
287
+ }
288
+
289
+ /**
290
+ * Three supported expiry policies:
291
+ * - indefinite: entries don't expire and must be explicitly removed
292
+ * - absolute: entries expire after the given duration in MS, even if accessed multiple times in the mean time
293
+ * - sliding: entries expire after the given duration in MS of inactivity (i.e. get resets the clock)
294
+ * @alpha
295
+ */
296
+ export declare type PromiseCacheExpiry = {
297
+ policy: "indefinite";
298
+ } | {
299
+ policy: "absolute" | "sliding";
300
+ durationMs: number;
301
+ };
302
+
303
+ /**
304
+ * Options for configuring the {@link PromiseCache}
305
+ * @alpha
306
+ */
307
+ export declare interface PromiseCacheOptions {
308
+ /**
309
+ * Common expiration policy for all items added to this cache
310
+ */
311
+ expiry?: PromiseCacheExpiry;
312
+ /**
313
+ * If the stored Promise is rejected with a particular error, should the given key be removed?
314
+ */
315
+ removeOnError?: (error: any) => boolean;
316
+ }
317
+
318
+ /**
319
+ * This class is a wrapper over setTimeout and clearTimeout which
320
+ * makes it simpler to keep track of recurring timeouts with the
321
+ * same handlers and timeouts, while also providing a promise that
322
+ * resolves when it times out.
323
+ * @internal
324
+ */
325
+ export declare class PromiseTimer implements IPromiseTimer {
326
+ private deferred?;
327
+ private readonly timer;
328
+ /**
329
+ * {@inheritDoc Timer.hasTimer}
330
+ */
331
+ get hasTimer(): boolean;
332
+ constructor(defaultTimeout: number, defaultHandler: () => void);
333
+ /**
334
+ * {@inheritDoc IPromiseTimer.start}
335
+ */
336
+ start(ms?: number, handler?: () => void): Promise<IPromiseTimerResult>;
337
+ clear(): void;
338
+ protected wrapHandler(handler: () => void): void;
339
+ }
340
+
341
+ /**
342
+ * Sets timeouts like the setTimeout function allowing timeouts to exceed the setTimeout's max timeout limit.
343
+ * Timeouts may not be exactly accurate due to browser implementations and the OS.
344
+ * https://stackoverflow.com/questions/21097421/what-is-the-reason-javascript-settimeout-is-so-inaccurate
345
+ * @param timeoutFn - Executed when the timeout expires
346
+ * @param timeoutMs - Duration of the timeout in milliseconds
347
+ * @param setTimeoutIdFn - Executed to update the timeout if multiple timeouts are required when
348
+ * timeoutMs greater than maxTimeout
349
+ * @returns The initial timeout
350
+ * @internal
351
+ */
352
+ export declare function setLongTimeout(timeoutFn: () => void, timeoutMs: number, setTimeoutIdFn?: (timeoutId: ReturnType<typeof setTimeout>) => void): ReturnType<typeof setTimeout>;
353
+
354
+ /**
355
+ * This class is a thin wrapper over setTimeout and clearTimeout which
356
+ * makes it simpler to keep track of recurring timeouts with the same
357
+ * or similar handlers and timeouts. This class supports long timeouts
358
+ * or timeouts exceeding (2^31)-1 ms or approximately 24.8 days.
359
+ * @internal
360
+ */
361
+ export declare class Timer implements ITimer {
362
+ private readonly defaultTimeout;
363
+ private readonly defaultHandler;
364
+ private readonly getCurrentTick;
365
+ /**
366
+ * Returns true if the timer is running.
367
+ */
368
+ get hasTimer(): boolean;
369
+ private runningState;
370
+ constructor(defaultTimeout: number, defaultHandler: () => void, getCurrentTick?: () => number);
371
+ /**
372
+ * Calls setTimeout and tracks the resulting timeout.
373
+ * @param ms - overrides default timeout in ms
374
+ * @param handler - overrides default handler
375
+ */
376
+ start(ms?: number, handler?: () => void): void;
377
+ /**
378
+ * Calls clearTimeout on the underlying timeout if running.
379
+ */
380
+ clear(): void;
381
+ /**
382
+ * Restarts the timer with the new handler and duration.
383
+ * If a new handler is passed, the original handler may
384
+ * never execute.
385
+ * This is a potentially more efficient way to clear and start
386
+ * a new timer.
387
+ * @param ms - overrides previous or default timeout in ms
388
+ * @param handler - overrides previous or default handler
389
+ */
390
+ restart(ms?: number, handler?: () => void): void;
391
+ private startCore;
392
+ private handler;
393
+ private calculateRemainingTime;
394
+ }
395
+
396
+ /**
397
+ * This function can be used to assert at compile time that a given value has type never.
398
+ * One common usage is in the default case of a switch block,
399
+ * to ensure that all cases are explicitly handled.
400
+ *
401
+ * Example:
402
+ * ```typescript
403
+ * const bool: true | false = ...;
404
+ * switch(bool) {
405
+ * case true: {...}
406
+ * case false: {...}
407
+ * default: unreachableCase(bool);
408
+ * }
409
+ * ```
410
+ * @internal
411
+ */
412
+ export declare function unreachableCase(_: never, message?: string): never;
413
+
414
+ export { }
package/lib/delay.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ /**
6
+ * Returns a promise that resolves after `timeMs`.
7
+ * @param timeMs - Time in milliseconds to wait.
8
+ * @internal
9
+ */
10
+ export declare const delay: (timeMs: number) => Promise<void>;
11
+ //# sourceMappingURL=delay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delay.d.ts","sourceRoot":"","sources":["../src/delay.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;GAIG;AACH,eAAO,MAAM,KAAK,WAAkB,MAAM,KAAG,QAAQ,IAAI,CACK,CAAC"}
package/lib/delay.js ADDED
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.delay = void 0;
8
+ /**
9
+ * Returns a promise that resolves after `timeMs`.
10
+ * @param timeMs - Time in milliseconds to wait.
11
+ * @internal
12
+ */
13
+ const delay = async (timeMs) => new Promise((resolve) => setTimeout(() => resolve(), timeMs));
14
+ exports.delay = delay;
15
+ //# sourceMappingURL=delay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delay.js","sourceRoot":"","sources":["../src/delay.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH;;;;GAIG;AACI,MAAM,KAAK,GAAG,KAAK,EAAE,MAAc,EAAiB,EAAE,CAC5D,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;AADlD,QAAA,KAAK,SAC6C","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Returns a promise that resolves after `timeMs`.\n * @param timeMs - Time in milliseconds to wait.\n * @internal\n */\nexport const delay = async (timeMs: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(() => resolve(), timeMs));\n"]}
package/lib/heap.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ /**
6
+ * Interface for a comparer.
7
+ * @internal
8
+ */
9
+ export interface IComparer<T> {
10
+ /**
11
+ * The minimum value of type T.
12
+ */
13
+ min: T;
14
+ /**
15
+ * Compare the two value
16
+ *
17
+ * @returns 0 if the value is equal, negative number if a is smaller then b, positive number otherwise
18
+ */
19
+ compare(a: T, b: T): number;
20
+ }
21
+ /**
22
+ * A comparer for numbers.
23
+ * @internal
24
+ */
25
+ export declare const NumberComparer: IComparer<number>;
26
+ /**
27
+ * Interface to a node in {@link Heap}.
28
+ * @internal
29
+ */
30
+ export interface IHeapNode<T> {
31
+ value: T;
32
+ position: number;
33
+ }
34
+ /**
35
+ * Ordered {@link https://en.wikipedia.org/wiki/Heap_(data_structure) | Heap} data structure implementation.
36
+ * @internal
37
+ */
38
+ export declare class Heap<T> {
39
+ comp: IComparer<T>;
40
+ private L;
41
+ /**
42
+ * Creates an instance of `Heap` with comparer.
43
+ * @param comp - A comparer that specify how elements are ordered.
44
+ */
45
+ constructor(comp: IComparer<T>);
46
+ /**
47
+ * Return the smallest element in the heap as determined by the order of the comparer
48
+ *
49
+ * @returns Heap node containing the smallest element
50
+ */
51
+ peek(): IHeapNode<T> | undefined;
52
+ /**
53
+ * Get and remove the smallest element in the heap as determined by the order of the comparer
54
+ *
55
+ * @returns The smallest value in the heap
56
+ */
57
+ get(): T | undefined;
58
+ /**
59
+ * Add a value to the heap
60
+ *
61
+ * @param x - value to add
62
+ * @returns The heap node that contains the value
63
+ */
64
+ add(x: T): IHeapNode<T>;
65
+ /**
66
+ * Allows for the Heap to be updated after a node's value changes.
67
+ */
68
+ update(node: IHeapNode<T>): void;
69
+ /**
70
+ * Removes the given node from the heap.
71
+ *
72
+ * @param node - The node to remove from the heap.
73
+ */
74
+ remove(node: IHeapNode<T>): void;
75
+ /**
76
+ * Get the number of elements in the Heap.
77
+ *
78
+ * @returns The number of elements in the Heap.
79
+ */
80
+ count(): number;
81
+ private fixup;
82
+ private isGreaterThanParent;
83
+ private fixdown;
84
+ private swap;
85
+ }
86
+ //# sourceMappingURL=heap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heap.d.ts","sourceRoot":"","sources":["../src/heap.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;GAGG;AACH,MAAM,WAAW,SAAS,CAAC,CAAC;IAC3B;;OAEG;IACH,GAAG,EAAE,CAAC,CAAC;IAEP;;;;OAIG;IACH,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC;CAC5B;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,SAAS,CAAC,MAAM,CAW5C,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,SAAS,CAAC,CAAC;IAC3B,KAAK,EAAE,CAAC,CAAC;IACT,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,qBAAa,IAAI,CAAC,CAAC;IAOC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;IANrC,OAAO,CAAC,CAAC,CAAiB;IAE1B;;;OAGG;gBACgB,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;IAIrC;;;;OAIG;IACI,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,SAAS;IAIvC;;;;OAIG;IACI,GAAG,IAAI,CAAC,GAAG,SAAS;IAY3B;;;;;OAKG;IACI,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC;IAQ9B;;OAEG;IACI,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI;IASvC;;;;OAIG;IACI,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI;IAYvC;;;;OAIG;IACI,KAAK,IAAI,MAAM;IAItB,OAAO,CAAC,KAAK;IAUb,OAAO,CAAC,mBAAmB;IAK3B,OAAO,CAAC,OAAO;IAiBf,OAAO,CAAC,IAAI;CAOZ"}
package/lib/heap.js ADDED
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.Heap = exports.NumberComparer = void 0;
8
+ /**
9
+ * A comparer for numbers.
10
+ * @internal
11
+ */
12
+ exports.NumberComparer = {
13
+ /**
14
+ * The compare function for numbers.
15
+ * @returns The difference of the two numbers.
16
+ */
17
+ compare: (a, b) => a - b,
18
+ /**
19
+ * The minimum value of a JavaScript number, which is `Number.MIN_VALUE`.
20
+ */
21
+ min: Number.MIN_VALUE,
22
+ };
23
+ /**
24
+ * Ordered {@link https://en.wikipedia.org/wiki/Heap_(data_structure) | Heap} data structure implementation.
25
+ * @internal
26
+ */
27
+ class Heap {
28
+ /**
29
+ * Creates an instance of `Heap` with comparer.
30
+ * @param comp - A comparer that specify how elements are ordered.
31
+ */
32
+ constructor(comp) {
33
+ this.comp = comp;
34
+ this.L = [{ value: comp.min, position: 0 }];
35
+ }
36
+ /**
37
+ * Return the smallest element in the heap as determined by the order of the comparer
38
+ *
39
+ * @returns Heap node containing the smallest element
40
+ */
41
+ peek() {
42
+ return this.L[1];
43
+ }
44
+ /**
45
+ * Get and remove the smallest element in the heap as determined by the order of the comparer
46
+ *
47
+ * @returns The smallest value in the heap
48
+ */
49
+ get() {
50
+ if (this.L.length === 0) {
51
+ return undefined;
52
+ }
53
+ this.swap(1, this.count());
54
+ const x = this.L.pop();
55
+ this.fixdown(1);
56
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
57
+ return x.value;
58
+ }
59
+ /**
60
+ * Add a value to the heap
61
+ *
62
+ * @param x - value to add
63
+ * @returns The heap node that contains the value
64
+ */
65
+ add(x) {
66
+ const node = { value: x, position: this.L.length };
67
+ this.L.push(node);
68
+ this.fixup(this.count());
69
+ return node;
70
+ }
71
+ /**
72
+ * Allows for the Heap to be updated after a node's value changes.
73
+ */
74
+ update(node) {
75
+ const k = node.position;
76
+ if (this.isGreaterThanParent(k)) {
77
+ this.fixup(k);
78
+ }
79
+ else {
80
+ this.fixdown(k);
81
+ }
82
+ }
83
+ /**
84
+ * Removes the given node from the heap.
85
+ *
86
+ * @param node - The node to remove from the heap.
87
+ */
88
+ remove(node) {
89
+ // Move the node we want to remove to the end of the array
90
+ const position = node.position;
91
+ this.swap(node.position, this.L.length - 1);
92
+ this.L.splice(-1);
93
+ // Update the swapped node assuming we didn't remove the end of the list
94
+ if (position !== this.L.length) {
95
+ this.update(this.L[position]);
96
+ }
97
+ }
98
+ /**
99
+ * Get the number of elements in the Heap.
100
+ *
101
+ * @returns The number of elements in the Heap.
102
+ */
103
+ count() {
104
+ return this.L.length - 1;
105
+ }
106
+ fixup(pos) {
107
+ let k = pos;
108
+ while (this.isGreaterThanParent(k)) {
109
+ // eslint-disable-next-line no-bitwise
110
+ const parent = k >> 1;
111
+ this.swap(k, parent);
112
+ k = parent;
113
+ }
114
+ }
115
+ isGreaterThanParent(k) {
116
+ // eslint-disable-next-line no-bitwise
117
+ return k > 1 && this.comp.compare(this.L[k >> 1].value, this.L[k].value) > 0;
118
+ }
119
+ fixdown(pos) {
120
+ let k = pos;
121
+ // eslint-disable-next-line no-bitwise
122
+ while (k << 1 <= this.count()) {
123
+ // eslint-disable-next-line no-bitwise
124
+ let j = k << 1;
125
+ if (j < this.count() && this.comp.compare(this.L[j].value, this.L[j + 1].value) > 0) {
126
+ j++;
127
+ }
128
+ if (this.comp.compare(this.L[k].value, this.L[j].value) <= 0) {
129
+ break;
130
+ }
131
+ this.swap(k, j);
132
+ k = j;
133
+ }
134
+ }
135
+ swap(k, j) {
136
+ const tmp = this.L[k];
137
+ this.L[k] = this.L[j];
138
+ this.L[k].position = k;
139
+ this.L[j] = tmp;
140
+ this.L[j].position = j;
141
+ }
142
+ }
143
+ exports.Heap = Heap;
144
+ //# sourceMappingURL=heap.js.map