@sha1n/about-time 0.0.9 → 0.0.12

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.
package/README.md CHANGED
@@ -13,6 +13,7 @@ A collection of essential time related utilities.
13
13
  - [Install](#install)
14
14
  - [Utilities & Features](#utilities--features)
15
15
  - [delay](#delay)
16
+ - [delayed](#delayed)
16
17
  - [timeoutAround](#timeoutaround)
17
18
  - [timeBounded](#timebounded)
18
19
  - [sleep](#sleep)
@@ -35,15 +36,22 @@ npm i @sha1n/about-time
35
36
  # Utilities & Features
36
37
  ## delay
37
38
  ```ts
38
- // Execute a function with delay and return it's value
39
+ // Executes a function with delay and returns it's value
39
40
  await delay(action, { time: 10 });
40
41
  await delay(action, { time: 10, units: TimeUnit.Milliseconds });
41
42
  await delay(action, { time: 10, units: TimeUnit.Milliseconds, unref: true });
42
43
  ```
43
44
 
45
+ ## delayed
46
+ ```ts
47
+ // Returns a new function that executes the specified action with delay and returns it's value
48
+ const delayedAction = delayed(action, { time: 10, units: TimeUnit.Milliseconds, unref: true });
49
+ const result = await delayedAction();
50
+ ```
51
+
44
52
  ## timeoutAround
45
53
  ```ts
46
- // Execute a function and guards it with a specified timeout
54
+ // Executes a function and guards it with a specified timeout
47
55
  await timeoutAround(action, { time: 10 });
48
56
  await timeoutAround(action, { time: 10, units: TimeUnit.Milliseconds });
49
57
  await timeoutAround(action, { time: 10, units: TimeUnit.Milliseconds, unref: true });
@@ -59,7 +67,7 @@ const result = await timeBoundAction();
59
67
 
60
68
  ## sleep
61
69
  ```ts
62
- // Pause execution for a specified amount of time
70
+ // Pauses execution for a specified amount of time
63
71
  await sleep(10);
64
72
  await sleep(10, { units: TimeUnit.Seconds });
65
73
  await sleep(10, { units: TimeUnit.Seconds, unref: true });
@@ -81,7 +89,7 @@ const elapsed2 = elapsed(TimeUnit.Seconds);
81
89
 
82
90
  ## until / eventually
83
91
  ```ts
84
- // Wait for a condition to become true
92
+ // Waits for a condition to become true
85
93
  await until(condition, { deadline: 10000 });
86
94
  await until(condition, { deadline: 10000, interval: 100 });
87
95
  await until(condition, { deadline: 10000, interval: 100, units: TimeUnit.Milliseconds });
package/dist/index.js CHANGED
@@ -1,16 +1,31 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
2
12
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.exponentialBackoffRetryPolicy = exports.simpleRetryPolicy = exports.fixedRetryPolicy = exports.retriable = exports.retryAround = exports.eventually = exports.until = exports.stopwatch = exports.delay = exports.sleep = exports.withTimeout = exports.toMilliseconds = exports.TimeUnit = void 0;
4
- var timeunit_1 = require("./lib/timeunit");
5
- Object.defineProperty(exports, "TimeUnit", { enumerable: true, get: function () { return timeunit_1.TimeUnit; } });
6
- Object.defineProperty(exports, "toMilliseconds", { enumerable: true, get: function () { return timeunit_1.toMilliseconds; } });
7
- var utilities_1 = require("./lib/utilities");
8
- Object.defineProperty(exports, "withTimeout", { enumerable: true, get: function () { return utilities_1.withTimeout; } });
9
- Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return utilities_1.sleep; } });
10
- Object.defineProperty(exports, "delay", { enumerable: true, get: function () { return utilities_1.delay; } });
11
- Object.defineProperty(exports, "stopwatch", { enumerable: true, get: function () { return utilities_1.stopwatch; } });
12
- Object.defineProperty(exports, "until", { enumerable: true, get: function () { return utilities_1.until; } });
13
- Object.defineProperty(exports, "eventually", { enumerable: true, get: function () { return utilities_1.eventually; } });
13
+ exports.exponentialBackoffRetryPolicy = exports.simpleRetryPolicy = exports.fixedRetryPolicy = exports.retriable = exports.retryAround = exports.eventually = exports.until = exports.stopwatch = exports.timeBounded = exports.timeoutAround = exports.delayed = exports.delay = exports.sleep = exports.toMilliseconds = void 0;
14
+ __exportStar(require("./lib/types"), exports);
15
+ var toMilliseconds_1 = require("./lib/toMilliseconds");
16
+ Object.defineProperty(exports, "toMilliseconds", { enumerable: true, get: function () { return toMilliseconds_1.toMilliseconds; } });
17
+ var delay_1 = require("./lib/delay");
18
+ Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return delay_1.sleep; } });
19
+ Object.defineProperty(exports, "delay", { enumerable: true, get: function () { return delay_1.delay; } });
20
+ Object.defineProperty(exports, "delayed", { enumerable: true, get: function () { return delay_1.delayed; } });
21
+ var timeout_1 = require("./lib/timeout");
22
+ Object.defineProperty(exports, "timeoutAround", { enumerable: true, get: function () { return timeout_1.timeoutAround; } });
23
+ Object.defineProperty(exports, "timeBounded", { enumerable: true, get: function () { return timeout_1.timeBounded; } });
24
+ var stopwatch_1 = require("./lib/stopwatch");
25
+ Object.defineProperty(exports, "stopwatch", { enumerable: true, get: function () { return stopwatch_1.stopwatch; } });
26
+ var eventually_1 = require("./lib/eventually");
27
+ Object.defineProperty(exports, "until", { enumerable: true, get: function () { return eventually_1.until; } });
28
+ Object.defineProperty(exports, "eventually", { enumerable: true, get: function () { return eventually_1.eventually; } });
14
29
  var retry_1 = require("./lib/retry");
15
30
  Object.defineProperty(exports, "retryAround", { enumerable: true, get: function () { return retry_1.retryAround; } });
16
31
  Object.defineProperty(exports, "retriable", { enumerable: true, get: function () { return retry_1.retriable; } });
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.delayed = exports.delay = exports.sleep = void 0;
4
+ const toMilliseconds_1 = require("./toMilliseconds");
5
+ /**
6
+ * Zzzz...
7
+ *
8
+ * @param time the approximate time to sleep (expect it to be as accurate as setTimeout)
9
+ * @param options timer options minus the time property
10
+ * @returns a promise that resolves when the specified time has elapsed.
11
+ */
12
+ function sleep(time, options) {
13
+ return new Promise(resolve => {
14
+ const timeout = setTimeout(resolve, (0, toMilliseconds_1.toMilliseconds)(time, options === null || options === void 0 ? void 0 : options.units));
15
+ if (options === null || options === void 0 ? void 0 : options.unref) {
16
+ timeout.unref();
17
+ }
18
+ });
19
+ }
20
+ exports.sleep = sleep;
21
+ /**
22
+ * Delays the execution of the specified action and returns its value.
23
+ *
24
+ * @param action a function to execute with delay
25
+ * @param options timer options
26
+ * @returns a promise that resolves when the specified time has elapsed.
27
+ */
28
+ async function delay(action, options) {
29
+ await sleep(options.time, options);
30
+ const result = await action();
31
+ return result;
32
+ }
33
+ exports.delay = delay;
34
+ /**
35
+ * Returns a new function that executes the specified action with delay.
36
+ *
37
+ * @param action a function to execute with delay
38
+ * @param options timer options
39
+ * @returns a new function.
40
+ */
41
+ function delayed(action, options) {
42
+ return async () => {
43
+ return delay(action, options);
44
+ };
45
+ }
46
+ exports.delayed = delayed;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.eventually = exports.until = void 0;
4
+ const toMilliseconds_1 = require("./toMilliseconds");
5
+ const types_1 = require("./types");
6
+ /**
7
+ * Awaits a specified condition to evaluate to true with or without a timeout.
8
+ *
9
+ * @param condition the condition to wait for
10
+ * @param options poll-options
11
+ * @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
12
+ */
13
+ async function until(condition, options) {
14
+ const defaultInterval = 50;
15
+ const deadline = (options === null || options === void 0 ? void 0 : options.deadline) ? Date.now() + (0, toMilliseconds_1.toMilliseconds)(options.deadline, options.units) : Number.MAX_VALUE;
16
+ const interval = (options === null || options === void 0 ? void 0 : options.interval) ? (0, toMilliseconds_1.toMilliseconds)(options.interval, options.units) : defaultInterval;
17
+ return new Promise((resolve, reject) => {
18
+ const handle = setInterval(() => {
19
+ if (Date.now() > deadline) {
20
+ clearInterval(handle);
21
+ reject(new types_1.TimeoutError());
22
+ }
23
+ try {
24
+ if (condition()) {
25
+ clearInterval(handle);
26
+ resolve();
27
+ }
28
+ }
29
+ catch (e) {
30
+ clearInterval(handle);
31
+ reject(e);
32
+ }
33
+ }, interval);
34
+ if (options === null || options === void 0 ? void 0 : options.unref) {
35
+ handle.unref();
36
+ }
37
+ });
38
+ }
39
+ exports.until = until;
40
+ /**
41
+ * Alias to `until`
42
+ */
43
+ const eventually = until;
44
+ exports.eventually = eventually;
package/dist/lib/retry.js CHANGED
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.exponentialBackoffRetryPolicy = exports.simpleRetryPolicy = exports.fixedRetryPolicy = exports.retriable = exports.retryAround = void 0;
4
- const timeunit_1 = require("./timeunit");
5
- const utilities_1 = require("./utilities");
4
+ const toMilliseconds_1 = require("./toMilliseconds");
5
+ const delay_1 = require("./delay");
6
+ const types_1 = require("./types");
6
7
  class SimpleRetryPolicy {
7
8
  constructor(count, interval, units) {
8
9
  this.count = count;
9
- this.interval = (0, timeunit_1.toMilliseconds)(interval, units);
10
+ this.interval = (0, toMilliseconds_1.toMilliseconds)(interval, units);
10
11
  }
11
12
  *intervals() {
12
13
  let count = this.count;
@@ -18,7 +19,7 @@ class SimpleRetryPolicy {
18
19
  }
19
20
  }
20
21
  class ExponentialBackoffRetryPolicy {
21
- constructor(count, exponential = 2, limit = Infinity, units = timeunit_1.TimeUnit.Milliseconds) {
22
+ constructor(count, exponential = 2, limit = Infinity, units = types_1.TimeUnit.Milliseconds) {
22
23
  this.count = count;
23
24
  this.exponential = exponential;
24
25
  this.limit = limit;
@@ -37,7 +38,7 @@ class ExponentialBackoffRetryPolicy {
37
38
  class FixedRetryPolicy {
38
39
  constructor(intervals, units) {
39
40
  this._intervals = intervals.reduceRight((result, v) => {
40
- result.push((0, timeunit_1.toMilliseconds)(v, units));
41
+ result.push((0, toMilliseconds_1.toMilliseconds)(v, units));
41
42
  return result;
42
43
  }, []);
43
44
  }
@@ -73,7 +74,7 @@ async function retryAround(action, policy, predicate = () => true) {
73
74
  if (next.done || !predicate(e)) {
74
75
  throw e;
75
76
  }
76
- await (0, utilities_1.sleep)(next.value);
77
+ await (0, delay_1.sleep)(next.value);
77
78
  }
78
79
  } while (!next.done);
79
80
  throw new Error('Unexpected error. This is most likely a bug.');
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stopwatch = void 0;
4
+ const types_1 = require("./types");
5
+ /**
6
+ * Return a function that returns the elapsed time relative to this call.
7
+ * @returns a function
8
+ */
9
+ function stopwatch() {
10
+ const startTime = Date.now();
11
+ return (units) => {
12
+ return (Date.now() - startTime) / (units || types_1.TimeUnit.Milliseconds);
13
+ };
14
+ }
15
+ exports.stopwatch = stopwatch;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.timeoutAround = exports.timeBounded = void 0;
4
+ const toMilliseconds_1 = require("./toMilliseconds");
5
+ const types_1 = require("./types");
6
+ /**
7
+ * Executes an action with a specified timeout. If the action times out, rejects with TimeoutError.
8
+ *
9
+ * @param action an action to execute with timeout
10
+ * @param options timer options
11
+ * @returns the action result
12
+ */
13
+ async function timeoutAround(action, options) {
14
+ const promisedAction = new Promise((resolve, reject) => {
15
+ try {
16
+ resolve(action());
17
+ }
18
+ catch (e) {
19
+ reject(e);
20
+ }
21
+ });
22
+ const race = new Promise((resolve, reject) => {
23
+ const timer = setTimeout(() => {
24
+ reject(new types_1.TimeoutError());
25
+ }, (0, toMilliseconds_1.toMilliseconds)(options.time, options.units));
26
+ if (options.unref) {
27
+ timer.unref();
28
+ }
29
+ return Promise.resolve(promisedAction).then(r => {
30
+ clearTimeout(timer);
31
+ resolve(r);
32
+ }, err => {
33
+ clearTimeout(timer);
34
+ reject(err);
35
+ });
36
+ });
37
+ return race;
38
+ }
39
+ exports.timeoutAround = timeoutAround;
40
+ function timeBounded(action, options) {
41
+ return () => {
42
+ return timeoutAround(action, options);
43
+ };
44
+ }
45
+ exports.timeBounded = timeBounded;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toMilliseconds = void 0;
4
+ /**
5
+ * Converts time value in other units to milliseconds.
6
+ *
7
+ * @param time a time value to be converted
8
+ * @param units the units of time
9
+ * @returns the time value in milliseconds
10
+ */
11
+ function toMilliseconds(time, units) {
12
+ return time * (units ? units : 1);
13
+ }
14
+ exports.toMilliseconds = toMilliseconds;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toMilliseconds = exports.TimeUnit = void 0;
3
+ exports.TimeoutError = exports.TimeUnit = void 0;
4
4
  var TimeUnit;
5
5
  (function (TimeUnit) {
6
6
  TimeUnit[TimeUnit["Milliseconds"] = 1] = "Milliseconds";
@@ -15,14 +15,9 @@ var TimeUnit;
15
15
  TimeUnit[TimeUnit["Day"] = 86400000] = "Day";
16
16
  })(TimeUnit || (TimeUnit = {}));
17
17
  exports.TimeUnit = TimeUnit;
18
- /**
19
- * Converts time value in other units to milliseconds.
20
- *
21
- * @param time a time value to be converted
22
- * @param units the units of time
23
- * @returns the time value in milliseconds
24
- */
25
- function toMilliseconds(time, units) {
26
- return time * (units ? units : 1);
18
+ class TimeoutError extends Error {
19
+ constructor(message) {
20
+ super(message || 'Timeout');
21
+ }
27
22
  }
28
- exports.toMilliseconds = toMilliseconds;
23
+ exports.TimeoutError = TimeoutError;
@@ -1,3 +1,7 @@
1
- export { TimeUnit, toMilliseconds } from './lib/timeunit';
2
- export { withTimeout, sleep, delay, stopwatch, until, eventually } from './lib/utilities';
1
+ export * from './lib/types';
2
+ export { toMilliseconds } from './lib/toMilliseconds';
3
+ export { sleep, delay, delayed } from './lib/delay';
4
+ export { timeoutAround, timeBounded } from './lib/timeout';
5
+ export { stopwatch } from './lib/stopwatch';
6
+ export { until, eventually } from './lib/eventually';
3
7
  export { RetryPolicy, retryAround, retriable, fixedRetryPolicy, simpleRetryPolicy, exponentialBackoffRetryPolicy } from './lib/retry';
@@ -0,0 +1,26 @@
1
+ import { TimerOptions } from './types';
2
+ /**
3
+ * Zzzz...
4
+ *
5
+ * @param time the approximate time to sleep (expect it to be as accurate as setTimeout)
6
+ * @param options timer options minus the time property
7
+ * @returns a promise that resolves when the specified time has elapsed.
8
+ */
9
+ declare function sleep(time: number, options?: Omit<TimerOptions, 'time'>): Promise<void>;
10
+ /**
11
+ * Delays the execution of the specified action and returns its value.
12
+ *
13
+ * @param action a function to execute with delay
14
+ * @param options timer options
15
+ * @returns a promise that resolves when the specified time has elapsed.
16
+ */
17
+ declare function delay<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T>;
18
+ /**
19
+ * Returns a new function that executes the specified action with delay.
20
+ *
21
+ * @param action a function to execute with delay
22
+ * @param options timer options
23
+ * @returns a new function.
24
+ */
25
+ declare function delayed<T>(action: () => T | Promise<T>, options: TimerOptions): () => Promise<T>;
26
+ export { sleep, delay, delayed };
@@ -0,0 +1,14 @@
1
+ import { PollOptions } from './types';
2
+ /**
3
+ * Awaits a specified condition to evaluate to true with or without a timeout.
4
+ *
5
+ * @param condition the condition to wait for
6
+ * @param options poll-options
7
+ * @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
8
+ */
9
+ declare function until(condition: () => boolean, options?: PollOptions): Promise<void>;
10
+ /**
11
+ * Alias to `until`
12
+ */
13
+ declare const eventually: typeof until;
14
+ export { until, eventually };
@@ -1,4 +1,4 @@
1
- import { TimeUnit } from './timeunit';
1
+ import { TimeUnit } from './types';
2
2
  interface RetryPolicy {
3
3
  intervals(): Iterable<number>;
4
4
  }
@@ -0,0 +1,7 @@
1
+ import { TimeUnit } from './types';
2
+ /**
3
+ * Return a function that returns the elapsed time relative to this call.
4
+ * @returns a function
5
+ */
6
+ declare function stopwatch(): (units?: TimeUnit) => number;
7
+ export { stopwatch };
@@ -0,0 +1,11 @@
1
+ import { TimerOptions } from './types';
2
+ /**
3
+ * Executes an action with a specified timeout. If the action times out, rejects with TimeoutError.
4
+ *
5
+ * @param action an action to execute with timeout
6
+ * @param options timer options
7
+ * @returns the action result
8
+ */
9
+ declare function timeoutAround<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T>;
10
+ declare function timeBounded<T>(action: () => T | Promise<T>, options: TimerOptions): () => Promise<T>;
11
+ export { timeBounded, timeoutAround };
@@ -0,0 +1,10 @@
1
+ import { TimeUnit } from './types';
2
+ /**
3
+ * Converts time value in other units to milliseconds.
4
+ *
5
+ * @param time a time value to be converted
6
+ * @param units the units of time
7
+ * @returns the time value in milliseconds
8
+ */
9
+ declare function toMilliseconds(time: number, units?: TimeUnit): number;
10
+ export { toMilliseconds };
@@ -0,0 +1,48 @@
1
+ declare enum TimeUnit {
2
+ Milliseconds = 1,
3
+ Millisecond = 1,
4
+ Seconds = 1000,
5
+ Second = 1000,
6
+ Minutes = 60000,
7
+ Minute = 60000,
8
+ Hours = 3600000,
9
+ Hour = 3600000,
10
+ Days = 86400000,
11
+ Day = 86400000
12
+ }
13
+ declare class TimeoutError extends Error {
14
+ constructor(message?: string);
15
+ }
16
+ declare type TimerOptions = {
17
+ /**
18
+ * The time to set
19
+ */
20
+ readonly time: number;
21
+ /**
22
+ * Optional units for the specified time
23
+ */
24
+ readonly units?: TimeUnit;
25
+ /**
26
+ * Whether to call unref on the timer
27
+ */
28
+ readonly unref?: boolean;
29
+ };
30
+ declare type PollOptions = {
31
+ /**
32
+ * The poll interval to set
33
+ */
34
+ readonly interval?: number;
35
+ /**
36
+ * The overall deadline to set
37
+ */
38
+ readonly deadline?: number;
39
+ /**
40
+ * Time units for specified time properties
41
+ */
42
+ readonly units?: TimeUnit;
43
+ /**
44
+ * Whether to call unref on any intervals/timers
45
+ */
46
+ readonly unref?: boolean;
47
+ };
48
+ export { TimeUnit, PollOptions, TimeoutError, TimerOptions };
package/index.ts CHANGED
@@ -1,5 +1,9 @@
1
- export { TimeUnit, toMilliseconds } from './lib/timeunit';
2
- export { timeoutAround, timeBounded, sleep, delay, stopwatch, until, eventually } from './lib/utilities';
1
+ export * from './lib/types';
2
+ export { toMilliseconds } from './lib/toMilliseconds';
3
+ export { sleep, delay, delayed } from './lib/delay';
4
+ export { timeoutAround, timeBounded } from './lib/timeout';
5
+ export { stopwatch } from './lib/stopwatch';
6
+ export { until, eventually } from './lib/eventually';
3
7
  export {
4
8
  RetryPolicy,
5
9
  retryAround,
package/lib/delay.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { toMilliseconds } from './toMilliseconds';
2
+ import { TimerOptions } from './types';
3
+
4
+ /**
5
+ * Zzzz...
6
+ *
7
+ * @param time the approximate time to sleep (expect it to be as accurate as setTimeout)
8
+ * @param options timer options minus the time property
9
+ * @returns a promise that resolves when the specified time has elapsed.
10
+ */
11
+ function sleep(time: number, options?: Omit<TimerOptions, 'time'>): Promise<void> {
12
+ return new Promise(resolve => {
13
+ const timeout = setTimeout(resolve, toMilliseconds(time, options?.units));
14
+
15
+ if (options?.unref) {
16
+ timeout.unref();
17
+ }
18
+ });
19
+ }
20
+
21
+ /**
22
+ * Delays the execution of the specified action and returns its value.
23
+ *
24
+ * @param action a function to execute with delay
25
+ * @param options timer options
26
+ * @returns a promise that resolves when the specified time has elapsed.
27
+ */
28
+ async function delay<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T> {
29
+ await sleep(options.time, options);
30
+ const result = await action();
31
+
32
+ return result;
33
+ }
34
+
35
+ /**
36
+ * Returns a new function that executes the specified action with delay.
37
+ *
38
+ * @param action a function to execute with delay
39
+ * @param options timer options
40
+ * @returns a new function.
41
+ */
42
+ function delayed<T>(action: () => T | Promise<T>, options: TimerOptions): () => Promise<T> {
43
+ return async () => {
44
+ return delay(action, options);
45
+ };
46
+ }
47
+
48
+ export { sleep, delay, delayed };
@@ -0,0 +1,45 @@
1
+ import { toMilliseconds } from './toMilliseconds';
2
+ import { PollOptions, TimeoutError } from './types';
3
+
4
+ /**
5
+ * Awaits a specified condition to evaluate to true with or without a timeout.
6
+ *
7
+ * @param condition the condition to wait for
8
+ * @param options poll-options
9
+ * @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
10
+ */
11
+ async function until(condition: () => boolean, options?: PollOptions): Promise<void> {
12
+ const defaultInterval = 50;
13
+ const deadline = options?.deadline ? Date.now() + toMilliseconds(options.deadline, options.units) : Number.MAX_VALUE;
14
+ const interval = options?.interval ? toMilliseconds(options.interval, options.units) : defaultInterval;
15
+
16
+ return new Promise<void>((resolve, reject) => {
17
+ const handle = setInterval(() => {
18
+ if (Date.now() > deadline) {
19
+ clearInterval(handle);
20
+ reject(new TimeoutError());
21
+ }
22
+
23
+ try {
24
+ if (condition()) {
25
+ clearInterval(handle);
26
+ resolve();
27
+ }
28
+ } catch (e) {
29
+ clearInterval(handle);
30
+ reject(e);
31
+ }
32
+ }, interval);
33
+
34
+ if (options?.unref) {
35
+ handle.unref();
36
+ }
37
+ });
38
+ }
39
+
40
+ /**
41
+ * Alias to `until`
42
+ */
43
+ const eventually = until;
44
+
45
+ export { until, eventually };
package/lib/retry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TimeUnit, toMilliseconds } from './timeunit';
2
- import { sleep } from './utilities';
1
+ import { toMilliseconds } from './toMilliseconds';
2
+ import { sleep } from './delay';
3
+ import { TimeUnit } from './types';
3
4
 
4
5
  interface RetryPolicy {
5
6
  intervals(): Iterable<number>;
@@ -0,0 +1,15 @@
1
+ import { TimeUnit } from './types';
2
+
3
+ /**
4
+ * Return a function that returns the elapsed time relative to this call.
5
+ * @returns a function
6
+ */
7
+ function stopwatch(): (units?: TimeUnit) => number {
8
+ const startTime = Date.now();
9
+
10
+ return (units?: TimeUnit) => {
11
+ return (Date.now() - startTime) / (units || TimeUnit.Milliseconds);
12
+ };
13
+ }
14
+
15
+ export { stopwatch };
package/lib/timeout.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { toMilliseconds } from './toMilliseconds';
2
+ import { TimerOptions, TimeoutError } from './types';
3
+
4
+ /**
5
+ * Executes an action with a specified timeout. If the action times out, rejects with TimeoutError.
6
+ *
7
+ * @param action an action to execute with timeout
8
+ * @param options timer options
9
+ * @returns the action result
10
+ */
11
+ async function timeoutAround<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T> {
12
+ const promisedAction = new Promise<T>((resolve, reject) => {
13
+ try {
14
+ resolve(action());
15
+ } catch (e) {
16
+ reject(e);
17
+ }
18
+ });
19
+
20
+ const race = new Promise<T>((resolve, reject) => {
21
+ const timer = setTimeout(() => {
22
+ reject(new TimeoutError());
23
+ }, toMilliseconds(options.time, options.units));
24
+
25
+ if (options.unref) {
26
+ timer.unref();
27
+ }
28
+
29
+ return Promise.resolve(promisedAction).then(
30
+ r => {
31
+ clearTimeout(timer);
32
+ resolve(r);
33
+ },
34
+ err => {
35
+ clearTimeout(timer);
36
+ reject(err);
37
+ }
38
+ );
39
+ });
40
+
41
+ return race;
42
+ }
43
+
44
+ function timeBounded<T>(action: () => T | Promise<T>, options: TimerOptions): () => Promise<T> {
45
+ return () => {
46
+ return timeoutAround(action, options);
47
+ };
48
+ }
49
+
50
+ export { timeBounded, timeoutAround };
@@ -1,15 +1,4 @@
1
- enum TimeUnit {
2
- Milliseconds = 1,
3
- Millisecond = Milliseconds,
4
- Seconds = 1000,
5
- Second = Seconds,
6
- Minutes = 1000 * 60,
7
- Minute = Minutes,
8
- Hours = 1000 * 60 * 60,
9
- Hour = Hours,
10
- Days = 1000 * 60 * 60 * 24,
11
- Day = Days
12
- }
1
+ import { TimeUnit } from './types';
13
2
 
14
3
  /**
15
4
  * Converts time value in other units to milliseconds.
@@ -22,4 +11,4 @@ function toMilliseconds(time: number, units?: TimeUnit): number {
22
11
  return time * (units ? units : 1);
23
12
  }
24
13
 
25
- export { TimeUnit, toMilliseconds };
14
+ export { toMilliseconds };
package/lib/types.ts ADDED
@@ -0,0 +1,54 @@
1
+ enum TimeUnit {
2
+ Milliseconds = 1,
3
+ Millisecond = Milliseconds,
4
+ Seconds = 1000,
5
+ Second = Seconds,
6
+ Minutes = 1000 * 60,
7
+ Minute = Minutes,
8
+ Hours = 1000 * 60 * 60,
9
+ Hour = Hours,
10
+ Days = 1000 * 60 * 60 * 24,
11
+ Day = Days
12
+ }
13
+
14
+ class TimeoutError extends Error {
15
+ constructor(message?: string) {
16
+ super(message || 'Timeout');
17
+ }
18
+ }
19
+
20
+ type TimerOptions = {
21
+ /**
22
+ * The time to set
23
+ */
24
+ readonly time: number;
25
+ /**
26
+ * Optional units for the specified time
27
+ */
28
+ readonly units?: TimeUnit;
29
+ /**
30
+ * Whether to call unref on the timer
31
+ */
32
+ readonly unref?: boolean;
33
+ };
34
+
35
+ type PollOptions = {
36
+ /**
37
+ * The poll interval to set
38
+ */
39
+ readonly interval?: number;
40
+ /**
41
+ * The overall deadline to set
42
+ */
43
+ readonly deadline?: number;
44
+ /**
45
+ * Time units for specified time properties
46
+ */
47
+ readonly units?: TimeUnit;
48
+ /**
49
+ * Whether to call unref on any intervals/timers
50
+ */
51
+ readonly unref?: boolean;
52
+ };
53
+
54
+ export { TimeUnit, PollOptions, TimeoutError, TimerOptions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sha1n/about-time",
3
- "version": "0.0.9",
3
+ "version": "0.0.12",
4
4
  "description": "A set of essential time related utilities",
5
5
  "repository": "https://github.com/sha1n/about-time",
6
6
  "author": "Shai Nagar",
@@ -1,127 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.eventually = exports.until = exports.stopwatch = exports.delay = exports.sleep = exports.withTimeout = void 0;
4
- const timeunit_1 = require("./timeunit");
5
- class TimeoutError extends Error {
6
- constructor(message) {
7
- super(message || 'Timeout');
8
- }
9
- }
10
- /**
11
- * Zzzz...
12
- *
13
- * @param time the approximate time to sleep (expect it to be as accurate as setTimeout)
14
- * @param options timer options minus the time property
15
- * @returns a promise that resolves when the specified time has elapsed.
16
- */
17
- function sleep(time, options) {
18
- return new Promise(resolve => {
19
- const timeout = setTimeout(resolve, (0, timeunit_1.toMilliseconds)(time, options === null || options === void 0 ? void 0 : options.units));
20
- if (options === null || options === void 0 ? void 0 : options.unref) {
21
- timeout.unref();
22
- }
23
- });
24
- }
25
- exports.sleep = sleep;
26
- /**
27
- * Delays the execution of the specified action and returns its value.
28
- *
29
- * @param action a function to execute with delay
30
- * @param options timer options
31
- * @returns a promise that resolves when the specified time has elapsed.
32
- */
33
- function delay(action, options) {
34
- const { time, units, unref } = options;
35
- const delayMs = (0, timeunit_1.toMilliseconds)(time, units);
36
- return new Promise((resolve, reject) => {
37
- const timer = setTimeout(() => Promise.resolve(action()).then(resolve, reject), delayMs);
38
- if (unref) {
39
- timer.unref();
40
- }
41
- });
42
- }
43
- exports.delay = delay;
44
- /**
45
- * Return a function that returns the elapsed time relative to this call.
46
- * @returns a function
47
- */
48
- function stopwatch() {
49
- const startTime = Date.now();
50
- return (units) => {
51
- return (Date.now() - startTime) / (units || timeunit_1.TimeUnit.Milliseconds);
52
- };
53
- }
54
- exports.stopwatch = stopwatch;
55
- /**
56
- * Awaits a specified condition to evaluate to true with or without a timeout.
57
- *
58
- * @param condition the condition to wait for
59
- * @param options poll-options
60
- * @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
61
- */
62
- async function until(condition, options) {
63
- const defaultInterval = 50;
64
- const deadline = (options === null || options === void 0 ? void 0 : options.deadline) ? Date.now() + (0, timeunit_1.toMilliseconds)(options.deadline, options.units) : Number.MAX_VALUE;
65
- const interval = (options === null || options === void 0 ? void 0 : options.interval) ? (0, timeunit_1.toMilliseconds)(options.interval, options.units) : defaultInterval;
66
- return new Promise((resolve, reject) => {
67
- const handle = setInterval(() => {
68
- if (Date.now() > deadline) {
69
- clearInterval(handle);
70
- reject(new TimeoutError());
71
- }
72
- try {
73
- if (condition()) {
74
- clearInterval(handle);
75
- resolve();
76
- }
77
- }
78
- catch (e) {
79
- clearInterval(handle);
80
- reject(e);
81
- }
82
- }, interval);
83
- if (options === null || options === void 0 ? void 0 : options.unref) {
84
- handle.unref();
85
- }
86
- });
87
- }
88
- exports.until = until;
89
- /**
90
- * Alias to `until`
91
- */
92
- const eventually = until;
93
- exports.eventually = eventually;
94
- /**
95
- * Executes an action with a specified timeout. If the action times out, rejects with TimeoutError.
96
- *
97
- * @param action an action to execute with timeout
98
- * @param options timer options
99
- * @returns the action result
100
- */
101
- async function withTimeout(action, options) {
102
- const promisedAction = new Promise((resolve, reject) => {
103
- try {
104
- resolve(action());
105
- }
106
- catch (e) {
107
- reject(e);
108
- }
109
- });
110
- const race = new Promise((resolve, reject) => {
111
- const timer = setTimeout(() => {
112
- reject(new TimeoutError());
113
- }, (0, timeunit_1.toMilliseconds)(options.time, options.units));
114
- if (options.unref) {
115
- timer.unref();
116
- }
117
- return Promise.resolve(promisedAction).then(r => {
118
- clearTimeout(timer);
119
- resolve(r);
120
- }, err => {
121
- clearTimeout(timer);
122
- reject(err);
123
- });
124
- });
125
- return race;
126
- }
127
- exports.withTimeout = withTimeout;
@@ -1,21 +0,0 @@
1
- declare enum TimeUnit {
2
- Milliseconds = 1,
3
- Millisecond = 1,
4
- Seconds = 1000,
5
- Second = 1000,
6
- Minutes = 60000,
7
- Minute = 60000,
8
- Hours = 3600000,
9
- Hour = 3600000,
10
- Days = 86400000,
11
- Day = 86400000
12
- }
13
- /**
14
- * Converts time value in other units to milliseconds.
15
- *
16
- * @param time a time value to be converted
17
- * @param units the units of time
18
- * @returns the time value in milliseconds
19
- */
20
- declare function toMilliseconds(time: number, units?: TimeUnit): number;
21
- export { TimeUnit, toMilliseconds };
@@ -1,75 +0,0 @@
1
- import { TimeUnit } from './timeunit';
2
- declare type TimerOptions = {
3
- /**
4
- * The time to set
5
- */
6
- readonly time: number;
7
- /**
8
- * Optional units for the specified time
9
- */
10
- readonly units?: TimeUnit;
11
- /**
12
- * Whether to call unref on the timer
13
- */
14
- readonly unref?: boolean;
15
- };
16
- declare type PollOptions = {
17
- /**
18
- * The poll interval to set
19
- */
20
- readonly interval?: number;
21
- /**
22
- * The overall deadline to set
23
- */
24
- readonly deadline?: number;
25
- /**
26
- * Time units for specified time properties
27
- */
28
- readonly units?: TimeUnit;
29
- /**
30
- * Whether to call unref on any intervals/timers
31
- */
32
- readonly unref?: boolean;
33
- };
34
- /**
35
- * Zzzz...
36
- *
37
- * @param time the approximate time to sleep (expect it to be as accurate as setTimeout)
38
- * @param options timer options minus the time property
39
- * @returns a promise that resolves when the specified time has elapsed.
40
- */
41
- declare function sleep(time: number, options?: Omit<TimerOptions, 'time'>): Promise<void>;
42
- /**
43
- * Delays the execution of the specified action and returns its value.
44
- *
45
- * @param action a function to execute with delay
46
- * @param options timer options
47
- * @returns a promise that resolves when the specified time has elapsed.
48
- */
49
- declare function delay<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T>;
50
- /**
51
- * Return a function that returns the elapsed time relative to this call.
52
- * @returns a function
53
- */
54
- declare function stopwatch(): (units?: TimeUnit) => number;
55
- /**
56
- * Awaits a specified condition to evaluate to true with or without a timeout.
57
- *
58
- * @param condition the condition to wait for
59
- * @param options poll-options
60
- * @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
61
- */
62
- declare function until(condition: () => boolean, options?: PollOptions): Promise<void>;
63
- /**
64
- * Alias to `until`
65
- */
66
- declare const eventually: typeof until;
67
- /**
68
- * Executes an action with a specified timeout. If the action times out, rejects with TimeoutError.
69
- *
70
- * @param action an action to execute with timeout
71
- * @param options timer options
72
- * @returns the action result
73
- */
74
- declare function withTimeout<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T>;
75
- export { withTimeout, sleep, delay, stopwatch, until, eventually };
package/lib/utilities.ts DELETED
@@ -1,178 +0,0 @@
1
- import { TimeUnit, toMilliseconds } from './timeunit';
2
-
3
- class TimeoutError extends Error {
4
- constructor(message?: string) {
5
- super(message || 'Timeout');
6
- }
7
- }
8
-
9
- type TimerOptions = {
10
- /**
11
- * The time to set
12
- */
13
- readonly time: number;
14
- /**
15
- * Optional units for the specified time
16
- */
17
- readonly units?: TimeUnit;
18
- /**
19
- * Whether to call unref on the timer
20
- */
21
- readonly unref?: boolean;
22
- };
23
-
24
- type PollOptions = {
25
- /**
26
- * The poll interval to set
27
- */
28
- readonly interval?: number;
29
- /**
30
- * The overall deadline to set
31
- */
32
- readonly deadline?: number;
33
- /**
34
- * Time units for specified time properties
35
- */
36
- readonly units?: TimeUnit;
37
- /**
38
- * Whether to call unref on any intervals/timers
39
- */
40
- readonly unref?: boolean;
41
- };
42
-
43
- /**
44
- * Zzzz...
45
- *
46
- * @param time the approximate time to sleep (expect it to be as accurate as setTimeout)
47
- * @param options timer options minus the time property
48
- * @returns a promise that resolves when the specified time has elapsed.
49
- */
50
- function sleep(time: number, options?: Omit<TimerOptions, 'time'>): Promise<void> {
51
- return new Promise(resolve => {
52
- const timeout = setTimeout(resolve, toMilliseconds(time, options?.units));
53
-
54
- if (options?.unref) {
55
- timeout.unref();
56
- }
57
- });
58
- }
59
-
60
- /**
61
- * Delays the execution of the specified action and returns its value.
62
- *
63
- * @param action a function to execute with delay
64
- * @param options timer options
65
- * @returns a promise that resolves when the specified time has elapsed.
66
- */
67
- function delay<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T> {
68
- const { time, units, unref } = options;
69
- const delayMs = toMilliseconds(time, units);
70
- return new Promise((resolve, reject) => {
71
- const timer = setTimeout(() => Promise.resolve(action()).then(resolve, reject), delayMs);
72
-
73
- if (unref) {
74
- timer.unref();
75
- }
76
- });
77
- }
78
-
79
- /**
80
- * Return a function that returns the elapsed time relative to this call.
81
- * @returns a function
82
- */
83
- function stopwatch(): (units?: TimeUnit) => number {
84
- const startTime = Date.now();
85
-
86
- return (units?: TimeUnit) => {
87
- return (Date.now() - startTime) / (units || TimeUnit.Milliseconds);
88
- };
89
- }
90
-
91
- /**
92
- * Awaits a specified condition to evaluate to true with or without a timeout.
93
- *
94
- * @param condition the condition to wait for
95
- * @param options poll-options
96
- * @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
97
- */
98
- async function until(condition: () => boolean, options?: PollOptions): Promise<void> {
99
- const defaultInterval = 50;
100
- const deadline = options?.deadline ? Date.now() + toMilliseconds(options.deadline, options.units) : Number.MAX_VALUE;
101
- const interval = options?.interval ? toMilliseconds(options.interval, options.units) : defaultInterval;
102
-
103
- return new Promise<void>((resolve, reject) => {
104
- const handle = setInterval(() => {
105
- if (Date.now() > deadline) {
106
- clearInterval(handle);
107
- reject(new TimeoutError());
108
- }
109
-
110
- try {
111
- if (condition()) {
112
- clearInterval(handle);
113
- resolve();
114
- }
115
- } catch (e) {
116
- clearInterval(handle);
117
- reject(e);
118
- }
119
- }, interval);
120
-
121
- if (options?.unref) {
122
- handle.unref();
123
- }
124
- });
125
- }
126
-
127
- /**
128
- * Alias to `until`
129
- */
130
- const eventually = until;
131
-
132
- /**
133
- * Executes an action with a specified timeout. If the action times out, rejects with TimeoutError.
134
- *
135
- * @param action an action to execute with timeout
136
- * @param options timer options
137
- * @returns the action result
138
- */
139
- async function timeoutAround<T>(action: () => T | Promise<T>, options: TimerOptions): Promise<T> {
140
- const promisedAction = new Promise<T>((resolve, reject) => {
141
- try {
142
- resolve(action());
143
- } catch (e) {
144
- reject(e);
145
- }
146
- });
147
-
148
- const race = new Promise<T>((resolve, reject) => {
149
- const timer = setTimeout(() => {
150
- reject(new TimeoutError());
151
- }, toMilliseconds(options.time, options.units));
152
-
153
- if (options.unref) {
154
- timer.unref();
155
- }
156
-
157
- return Promise.resolve(promisedAction).then(
158
- r => {
159
- clearTimeout(timer);
160
- resolve(r);
161
- },
162
- err => {
163
- clearTimeout(timer);
164
- reject(err);
165
- }
166
- );
167
- });
168
-
169
- return race;
170
- }
171
-
172
- function timeBounded<T>(action: () => T | Promise<T>, options: TimerOptions): () => Promise<T> {
173
- return () => {
174
- return timeoutAround(action, options);
175
- };
176
- }
177
-
178
- export { timeoutAround, timeBounded, sleep, delay, stopwatch, until, eventually };