@rsdk/common 0.14.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.
- package/.eslintignore +4 -0
- package/.eslintrc.js +4 -0
- package/.prettierignore +1 -0
- package/.prettierrc.json +1 -0
- package/dist/convert/convert.class.d.ts +61 -0
- package/dist/convert/convert.class.js +144 -0
- package/dist/convert/convert.class.js.map +1 -0
- package/dist/convert/index.d.ts +1 -0
- package/dist/convert/index.js +18 -0
- package/dist/convert/index.js.map +1 -0
- package/dist/enums/enums.functions.d.ts +15 -0
- package/dist/enums/enums.functions.js +31 -0
- package/dist/enums/enums.functions.js.map +1 -0
- package/dist/enums/index.d.ts +2 -0
- package/dist/enums/index.js +19 -0
- package/dist/enums/index.js.map +1 -0
- package/dist/enums/types.d.ts +4 -0
- package/dist/enums/types.js +3 -0
- package/dist/enums/types.js.map +1 -0
- package/dist/functions/index.d.ts +2 -0
- package/dist/functions/index.js +19 -0
- package/dist/functions/index.js.map +1 -0
- package/dist/functions/misc.d.ts +33 -0
- package/dist/functions/misc.js +57 -0
- package/dist/functions/misc.js.map +1 -0
- package/dist/functions/obj-normalization.d.ts +27 -0
- package/dist/functions/obj-normalization.js +73 -0
- package/dist/functions/obj-normalization.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +38 -0
- package/dist/index.js.map +1 -0
- package/dist/serialization/errors/index.d.ts +3 -0
- package/dist/serialization/errors/index.js +20 -0
- package/dist/serialization/errors/index.js.map +1 -0
- package/dist/serialization/errors/not-absolute-path.error.d.ts +3 -0
- package/dist/serialization/errors/not-absolute-path.error.js +10 -0
- package/dist/serialization/errors/not-absolute-path.error.js.map +1 -0
- package/dist/serialization/errors/unknown-file-ext.error.d.ts +3 -0
- package/dist/serialization/errors/unknown-file-ext.error.js +10 -0
- package/dist/serialization/errors/unknown-file-ext.error.js.map +1 -0
- package/dist/serialization/errors/unknown-format.error.d.ts +5 -0
- package/dist/serialization/errors/unknown-format.error.js +11 -0
- package/dist/serialization/errors/unknown-format.error.js.map +1 -0
- package/dist/serialization/index.d.ts +5 -0
- package/dist/serialization/index.js +22 -0
- package/dist/serialization/index.js.map +1 -0
- package/dist/serialization/read-obj-sync.d.ts +9 -0
- package/dist/serialization/read-obj-sync.js +25 -0
- package/dist/serialization/read-obj-sync.js.map +1 -0
- package/dist/serialization/read-obj.d.ts +8 -0
- package/dist/serialization/read-obj.js +24 -0
- package/dist/serialization/read-obj.js.map +1 -0
- package/dist/serialization/reviving-serializer.d.ts +8 -0
- package/dist/serialization/reviving-serializer.js +30 -0
- package/dist/serialization/reviving-serializer.js.map +1 -0
- package/dist/serialization/save-obj.d.ts +10 -0
- package/dist/serialization/save-obj.js +25 -0
- package/dist/serialization/save-obj.js.map +1 -0
- package/dist/serialization/serializer.class.d.ts +14 -0
- package/dist/serialization/serializer.class.js +64 -0
- package/dist/serialization/serializer.class.js.map +1 -0
- package/dist/size/index.d.ts +1 -0
- package/dist/size/index.js +18 -0
- package/dist/size/index.js.map +1 -0
- package/dist/size/size.class.d.ts +16 -0
- package/dist/size/size.class.js +60 -0
- package/dist/size/size.class.js.map +1 -0
- package/dist/time/index.d.ts +4 -0
- package/dist/time/index.js +21 -0
- package/dist/time/index.js.map +1 -0
- package/dist/time/repeat.fn.d.ts +8 -0
- package/dist/time/repeat.fn.js +23 -0
- package/dist/time/repeat.fn.js.map +1 -0
- package/dist/time/stopwatch.class.d.ts +61 -0
- package/dist/time/stopwatch.class.js +97 -0
- package/dist/time/stopwatch.class.js.map +1 -0
- package/dist/time/timer.class.d.ts +9 -0
- package/dist/time/timer.class.js +18 -0
- package/dist/time/timer.class.js.map +1 -0
- package/dist/time/timespan.class.d.ts +49 -0
- package/dist/time/timespan.class.js +116 -0
- package/dist/time/timespan.class.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types/assert.class.d.ts +5 -0
- package/dist/types/assert.class.js +25 -0
- package/dist/types/assert.class.js.map +1 -0
- package/dist/types/constructor.type.d.ts +2 -0
- package/dist/types/constructor.type.js +3 -0
- package/dist/types/constructor.type.js.map +1 -0
- package/dist/types/deep-partial.type.d.ts +11 -0
- package/dist/types/deep-partial.type.js +3 -0
- package/dist/types/deep-partial.type.js.map +1 -0
- package/dist/types/error-like.type.d.ts +5 -0
- package/dist/types/error-like.type.js +6 -0
- package/dist/types/error-like.type.js.map +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.js +22 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/primitive.type.d.ts +2 -0
- package/dist/types/primitive.type.js +6 -0
- package/dist/types/primitive.type.js.map +1 -0
- package/dist/types/required-fields.d.ts +5 -0
- package/dist/types/required-fields.js +3 -0
- package/dist/types/required-fields.js.map +1 -0
- package/package.json +32 -0
- package/src/convert/convert.class.ts +172 -0
- package/src/convert/convert.spec.ts +271 -0
- package/src/convert/index.ts +1 -0
- package/src/enums/enums.functions.ts +34 -0
- package/src/enums/enums.spec.ts +59 -0
- package/src/enums/index.ts +2 -0
- package/src/enums/types.ts +5 -0
- package/src/functions/index.ts +2 -0
- package/src/functions/misc.ts +70 -0
- package/src/functions/obj-normalization.ts +104 -0
- package/src/index.ts +8 -0
- package/src/serialization/errors/index.ts +3 -0
- package/src/serialization/errors/not-absolute-path.error.ts +5 -0
- package/src/serialization/errors/unknown-file-ext.error.ts +5 -0
- package/src/serialization/errors/unknown-format.error.ts +9 -0
- package/src/serialization/index.ts +5 -0
- package/src/serialization/read-obj-sync.ts +24 -0
- package/src/serialization/read-obj.ts +23 -0
- package/src/serialization/reviving-serializer.ts +32 -0
- package/src/serialization/save-obj.ts +31 -0
- package/src/serialization/serializer.class.ts +85 -0
- package/src/size/index.ts +1 -0
- package/src/size/size.class.ts +77 -0
- package/src/size/size.spec.ts +74 -0
- package/src/time/index.ts +4 -0
- package/src/time/repeat.fn.ts +27 -0
- package/src/time/stopwatch.class.ts +108 -0
- package/src/time/timer.class.ts +15 -0
- package/src/time/timespan.class.ts +161 -0
- package/src/time/timespan.spec.ts +81 -0
- package/src/types/assert.class.ts +25 -0
- package/src/types/constructor.type.ts +2 -0
- package/src/types/deep-partial.type.ts +23 -0
- package/src/types/error-like.type.ts +8 -0
- package/src/types/index.ts +6 -0
- package/src/types/primitive.type.ts +4 -0
- package/src/types/required-fields.ts +8 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { isPrimitive } from '../types';
|
|
2
|
+
|
|
3
|
+
export interface SortKeys {
|
|
4
|
+
match: (x: unknown) => boolean;
|
|
5
|
+
sortFn: (a: string, b: string) => number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface NormalizeOptions {
|
|
9
|
+
filterKeys?: string[];
|
|
10
|
+
sortKeys?: SortKeys;
|
|
11
|
+
maxDepth?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const DEFAULT_MAX_DEPTH = 10;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Prepares object to be stringified with JSON.stringify()
|
|
18
|
+
* - removes circular references.
|
|
19
|
+
* - makes message, stack and cause properties of Errors enumerable
|
|
20
|
+
* - (optional) sorts error keys for human readability
|
|
21
|
+
* - (optional) filters out provided keys
|
|
22
|
+
*
|
|
23
|
+
* NOTE: Function is recursive
|
|
24
|
+
*
|
|
25
|
+
* @param x any value,
|
|
26
|
+
* @param options NormalizeOptions
|
|
27
|
+
* @returns unknown
|
|
28
|
+
*/
|
|
29
|
+
export const normalizer = (): ((
|
|
30
|
+
x: unknown,
|
|
31
|
+
options?: NormalizeOptions,
|
|
32
|
+
depth?: number,
|
|
33
|
+
) => unknown) => {
|
|
34
|
+
const cache = new Set();
|
|
35
|
+
|
|
36
|
+
const normalize = (
|
|
37
|
+
x: unknown,
|
|
38
|
+
options?: NormalizeOptions,
|
|
39
|
+
depth = 0,
|
|
40
|
+
): unknown => {
|
|
41
|
+
if (x === null || x === undefined || isPrimitive(x)) {
|
|
42
|
+
return x;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (cache.has(x)) {
|
|
46
|
+
return '[circular]';
|
|
47
|
+
} else {
|
|
48
|
+
cache.add(x);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (Array.isArray(x)) {
|
|
52
|
+
return x.map((x) => normalize(x, options));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (depth >= (options?.maxDepth ?? DEFAULT_MAX_DEPTH)) {
|
|
56
|
+
return '[max nesting depth reached]';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const unique = new Set(Object.keys(x));
|
|
60
|
+
|
|
61
|
+
if (x instanceof Error) {
|
|
62
|
+
unique.add('cause');
|
|
63
|
+
unique.add('stack');
|
|
64
|
+
unique.add('message');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const keys = [...unique];
|
|
68
|
+
|
|
69
|
+
if (options?.sortKeys && options.sortKeys.match(x)) {
|
|
70
|
+
keys.sort(options.sortKeys.sortFn);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const newDepth = depth + 1;
|
|
74
|
+
|
|
75
|
+
return keys.reduce((acc: Record<string, unknown>, key) => {
|
|
76
|
+
if (options?.filterKeys && options.filterKeys.includes(key)) {
|
|
77
|
+
return acc;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
acc[key] = normalize((x as any)[key], options, newDepth);
|
|
81
|
+
|
|
82
|
+
return acc;
|
|
83
|
+
}, {});
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
return normalize;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const errorKeysOrder = new Map<string, number>()
|
|
90
|
+
.set('metatype', 0)
|
|
91
|
+
.set('code', 1)
|
|
92
|
+
.set('message', 2)
|
|
93
|
+
.set('details', 3)
|
|
94
|
+
.set('stack', 4)
|
|
95
|
+
.set('cause', 5);
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* SortOptions for keys of Error instances
|
|
99
|
+
*/
|
|
100
|
+
export const sortErrorKeys: SortKeys = {
|
|
101
|
+
match: (x) => x instanceof Error,
|
|
102
|
+
sortFn: (a: string, b: string): number =>
|
|
103
|
+
(errorKeysOrder.get(a) ?? 0) > (errorKeysOrder.get(b) ?? 0) ? 1 : -1,
|
|
104
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readFileSync } from 'fs';
|
|
2
|
+
import { isAbsolute } from 'path';
|
|
3
|
+
|
|
4
|
+
import { NotAbsolutePathError } from './errors';
|
|
5
|
+
import { Serializer } from './serializer.class';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Reads file into an object.
|
|
9
|
+
* Can be used in constructors where you can't perform async operations.
|
|
10
|
+
* Supported formats: json, yaml, yml, .env
|
|
11
|
+
*
|
|
12
|
+
* @param {string} pathToFile Absolute path to file.
|
|
13
|
+
* @returns {any}
|
|
14
|
+
*/
|
|
15
|
+
export const readObjSync = (pathToFile: string): unknown => {
|
|
16
|
+
if (!isAbsolute(pathToFile)) {
|
|
17
|
+
throw new NotAbsolutePathError(pathToFile);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const content = readFileSync(pathToFile).toString();
|
|
21
|
+
const format = Serializer.getFormat(pathToFile);
|
|
22
|
+
|
|
23
|
+
return Serializer.parse(content, format);
|
|
24
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { promises as fs } from 'fs';
|
|
2
|
+
import { isAbsolute } from 'path';
|
|
3
|
+
|
|
4
|
+
import { NotAbsolutePathError } from './errors';
|
|
5
|
+
import { Serializer } from './serializer.class';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Reads file into an object.
|
|
9
|
+
* Supported formats: json, yaml, yml, .env
|
|
10
|
+
*
|
|
11
|
+
* @param {string} pathToFile Absolute path to file.
|
|
12
|
+
* @returns {any}
|
|
13
|
+
*/
|
|
14
|
+
export const readObj = async (pathToFile: string): Promise<unknown> => {
|
|
15
|
+
if (!isAbsolute(pathToFile)) {
|
|
16
|
+
throw new NotAbsolutePathError(pathToFile);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const format = Serializer.getFormat(pathToFile);
|
|
20
|
+
const content = await fs.readFile(pathToFile);
|
|
21
|
+
|
|
22
|
+
return Serializer.parse(content.toString(), format);
|
|
23
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* For serializing and deserializing objects with methods.
|
|
3
|
+
* See more in https://clck.ru/Qc3e4
|
|
4
|
+
* */
|
|
5
|
+
export class RevivingSerializer {
|
|
6
|
+
static serialize<T>(obj: T): string {
|
|
7
|
+
return JSON.stringify(obj, (_key: string, value: unknown): unknown => {
|
|
8
|
+
if (typeof value === 'function') {
|
|
9
|
+
return value.toString();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
return value;
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
static deserialize<T>(serializedObject: string): T {
|
|
17
|
+
return JSON.parse(
|
|
18
|
+
serializedObject,
|
|
19
|
+
(_key: string, value: unknown): unknown => {
|
|
20
|
+
if (typeof value === 'string' && value.startsWith('function')) {
|
|
21
|
+
const functionTemplate = `(${value})`;
|
|
22
|
+
|
|
23
|
+
// eval is the best the best way to revive function from serialized object.
|
|
24
|
+
// eslint-disable-next-line no-eval
|
|
25
|
+
return eval(functionTemplate) as unknown;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return value;
|
|
29
|
+
},
|
|
30
|
+
) as T;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { promises as fs } from 'fs';
|
|
2
|
+
import { isAbsolute } from 'path';
|
|
3
|
+
|
|
4
|
+
import { NotAbsolutePathError } from './errors';
|
|
5
|
+
import { Serializer } from './serializer.class';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Saves object into file.
|
|
9
|
+
* Supported formats: json, yaml, yml, .env
|
|
10
|
+
*
|
|
11
|
+
* @param {*} obj
|
|
12
|
+
* @param {string} filename Absolute path to file.
|
|
13
|
+
* @param {string} [format] If not specified serializer will try
|
|
14
|
+
* to recognize it by file extension.
|
|
15
|
+
*/
|
|
16
|
+
export const saveObj = async (
|
|
17
|
+
obj: Record<string, unknown>,
|
|
18
|
+
filename: string,
|
|
19
|
+
format?: string,
|
|
20
|
+
): Promise<void> => {
|
|
21
|
+
if (!isAbsolute(filename)) {
|
|
22
|
+
throw new NotAbsolutePathError(filename);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const text = Serializer.stringify(
|
|
26
|
+
obj,
|
|
27
|
+
format || Serializer.getFormat(filename),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
await fs.writeFile(filename, `${text}\n`);
|
|
31
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { extname } from 'path';
|
|
2
|
+
|
|
3
|
+
import dotenv from 'dotenv';
|
|
4
|
+
import TOML from 'toml';
|
|
5
|
+
import YAML from 'yaml';
|
|
6
|
+
|
|
7
|
+
import { UnknownFileExtensionError, UnknownFormatError } from './errors';
|
|
8
|
+
|
|
9
|
+
export type Parser = (text: string) => unknown;
|
|
10
|
+
export type Stringifier = (obj: Record<string, unknown>) => string;
|
|
11
|
+
export type Format = string;
|
|
12
|
+
export type Extension = string;
|
|
13
|
+
|
|
14
|
+
const INDENT = 2;
|
|
15
|
+
|
|
16
|
+
export class Serializer {
|
|
17
|
+
private static readonly parsers = new Map<Format, Parser>()
|
|
18
|
+
.set('json', (text) => JSON.parse(text))
|
|
19
|
+
.set('yaml', (text) => YAML.parse(text))
|
|
20
|
+
.set('toml', (text) => TOML.parse(text))
|
|
21
|
+
.set('env', (text) => dotenv.parse(text));
|
|
22
|
+
|
|
23
|
+
private static readonly stringifiers = new Map<Format, Stringifier>()
|
|
24
|
+
.set('json', (obj) => JSON.stringify(obj, null, INDENT))
|
|
25
|
+
.set('yaml', (obj) => YAML.stringify(obj))
|
|
26
|
+
.set('env', (obj) =>
|
|
27
|
+
Object.entries(obj)
|
|
28
|
+
.map(
|
|
29
|
+
([key, value]) =>
|
|
30
|
+
`${key}=${typeof value === 'object' ? JSON.stringify(obj) : value}`,
|
|
31
|
+
)
|
|
32
|
+
.join('\n'),
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
private static readonly extensions = new Map<Extension, Format>()
|
|
36
|
+
.set('.json', 'json')
|
|
37
|
+
.set('.yaml', 'yaml')
|
|
38
|
+
.set('.yml', 'yaml')
|
|
39
|
+
.set('.toml', 'toml')
|
|
40
|
+
.set('.env', 'env');
|
|
41
|
+
|
|
42
|
+
static getFormat(filename: string): Format {
|
|
43
|
+
let ext = extname(filename);
|
|
44
|
+
|
|
45
|
+
if (!ext && filename.includes('.env')) {
|
|
46
|
+
ext = '.env';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const format = Serializer.extensions.get(ext);
|
|
50
|
+
|
|
51
|
+
if (!format) {
|
|
52
|
+
throw new UnknownFileExtensionError(ext);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return format;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
static stringify(obj: Record<string, unknown>, format: Format): string {
|
|
59
|
+
const stringifier = Serializer.stringifiers.get(format);
|
|
60
|
+
|
|
61
|
+
if (!stringifier) {
|
|
62
|
+
throw new UnknownFormatError(format);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return stringifier(obj);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
static parse(text: string, format: Format): unknown {
|
|
69
|
+
const parser = Serializer.parsers.get(format);
|
|
70
|
+
|
|
71
|
+
if (!parser) {
|
|
72
|
+
throw new UnknownFormatError(format);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return parser(text);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
static useParser(format: Format, parser: Parser): void {
|
|
79
|
+
Serializer.parsers.set(format, parser);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
static useStringifier(format: Format, stringifier: Stringifier): void {
|
|
83
|
+
Serializer.stringifiers.set(format, stringifier);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './size.class';
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-non-null-assertion */
|
|
2
|
+
import { text } from '../functions';
|
|
3
|
+
|
|
4
|
+
type Unit = 'b' | 'kb' | 'mb' | 'gb';
|
|
5
|
+
type UnitAlias = 'B' | 'KB' | 'MB' | 'GB';
|
|
6
|
+
type SizeString = `${number}${Unit | UnitAlias}`;
|
|
7
|
+
|
|
8
|
+
const factors: Record<Unit, number> = {
|
|
9
|
+
b: 1,
|
|
10
|
+
kb: 1024,
|
|
11
|
+
mb: 1024 * 1024,
|
|
12
|
+
|
|
13
|
+
gb: 1024 * 1024 * 1024,
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const SIZE_STRING_PATTERN = /^(\d{1,100})(b|kb|mb|gb)$/i;
|
|
17
|
+
|
|
18
|
+
class InvalidSize extends Error {
|
|
19
|
+
constructor(str: string) {
|
|
20
|
+
super(text`
|
|
21
|
+
Invalid size string: <${str}>.
|
|
22
|
+
Size string should contain numeric and unit parts.
|
|
23
|
+
Acceptable units: B, KB, MB, GB (case doesn't matter).
|
|
24
|
+
Ex: "8B, 100GB"
|
|
25
|
+
`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class Size {
|
|
30
|
+
private readonly _bytes: number;
|
|
31
|
+
|
|
32
|
+
constructor(value: number, u: Unit | UnitAlias) {
|
|
33
|
+
const unit = u.toLowerCase() as Unit;
|
|
34
|
+
|
|
35
|
+
this._bytes = value * factors[unit];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
static parse(str: string): Size {
|
|
39
|
+
const match = SIZE_STRING_PATTERN.exec(str);
|
|
40
|
+
|
|
41
|
+
if (!match) {
|
|
42
|
+
throw new InvalidSize(str);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const [, rawValue, rawUnit] = match;
|
|
46
|
+
|
|
47
|
+
const value = parseInt(rawValue!, 10);
|
|
48
|
+
const unit = rawUnit!.toLowerCase() as Unit | UnitAlias;
|
|
49
|
+
|
|
50
|
+
return new Size(value, unit);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
bytes(): number {
|
|
54
|
+
return this._bytes;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
kilobytes(): number {
|
|
58
|
+
return this._bytes / factors.kb;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
megabytes(): number {
|
|
62
|
+
return this._bytes / factors.mb;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
gigabytes(): number {
|
|
66
|
+
return this._bytes / factors.gb;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
toString(u: Unit | UnitAlias = 'b'): string {
|
|
70
|
+
const unit = u.toLowerCase() as Unit;
|
|
71
|
+
const value = this._bytes / factors[unit];
|
|
72
|
+
|
|
73
|
+
return `${value}${unit}`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export const size = (str: SizeString): Size => Size.parse(str);
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/* eslint-disable sort-keys */
|
|
2
|
+
/* eslint-disable prettier/prettier */
|
|
3
|
+
|
|
4
|
+
import { Size } from './size.class';
|
|
5
|
+
|
|
6
|
+
describe('Size', () => {
|
|
7
|
+
describe('Casting', () => {
|
|
8
|
+
interface TestCase {
|
|
9
|
+
name: string;
|
|
10
|
+
s: Size;
|
|
11
|
+
b: number;
|
|
12
|
+
kb: number;
|
|
13
|
+
mb: number;
|
|
14
|
+
gb: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const tt: TestCase[] = [
|
|
18
|
+
// GB
|
|
19
|
+
{ name: '1gb', s: new Size(1, 'gb'), gb: 1, mb: 1024, kb: 1_048_576, b: 1_073_741_824 },
|
|
20
|
+
{ name: '2gb', s: new Size(2, 'gb'), gb: 2, mb: 2048, kb: 2_097_152, b: 2_147_483_648 },
|
|
21
|
+
|
|
22
|
+
// MB
|
|
23
|
+
{ name: '1mb', s: new Size(1, 'mb'), gb: 0.001, mb: 1, kb: 1024, b: 1_048_576 },
|
|
24
|
+
{ name: '2mb', s: new Size(2, 'mb'), gb: 0.002, mb: 2, kb: 2048, b: 2_097_152 },
|
|
25
|
+
|
|
26
|
+
// KB
|
|
27
|
+
{ name: '1kb', s: new Size(1, 'kb'), gb: 0.0, mb: 0.001, kb: 1, b: 1024 },
|
|
28
|
+
{ name: '2kb', s: new Size(2, 'kb'), gb: 0.0, mb: 0.002, kb: 2, b: 2048 },
|
|
29
|
+
|
|
30
|
+
// Bytes
|
|
31
|
+
{ name: '1b', s: new Size(1, 'b'), gb: 0.0, mb: 0.0, kb: 0.001, b: 1 },
|
|
32
|
+
{ name: '2b', s: new Size(2, 'b'), gb: 0.0, mb: 0.0, kb: 0.002, b: 2 },
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
for (const { name, s, b, kb, mb, gb } of tt) {
|
|
36
|
+
it(name, () => {
|
|
37
|
+
/**
|
|
38
|
+
* Всё округляется до 3-го знака после запятой
|
|
39
|
+
*/
|
|
40
|
+
expect(s.gigabytes().toFixed(3)).toEqual(gb.toFixed(3));
|
|
41
|
+
expect(s.megabytes().toFixed(3)).toEqual(mb.toFixed(3));
|
|
42
|
+
expect(s.kilobytes().toFixed(3)).toEqual(kb.toFixed(3));
|
|
43
|
+
expect(s.bytes().toFixed(3)).toEqual(b.toFixed(3));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe('Parsing', () => {
|
|
49
|
+
interface TestCase {
|
|
50
|
+
str: string;
|
|
51
|
+
correct: boolean;
|
|
52
|
+
bytes: number | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const tt: TestCase[] = [
|
|
56
|
+
{ str: '1gb', correct: true, bytes: 1_073_741_824 },
|
|
57
|
+
{ str: '1mb', correct: true, bytes: 1_048_576 },
|
|
58
|
+
{ str: '1kb', correct: true, bytes: 1024 },
|
|
59
|
+
{ str: '1b', correct: true, bytes: 1 },
|
|
60
|
+
{ str: '1tb', correct: false, bytes: null },
|
|
61
|
+
{ str: 'Size', correct: false, bytes: null },
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
for (const { str, correct, bytes } of tt) {
|
|
65
|
+
it(str, () => {
|
|
66
|
+
if (correct) {
|
|
67
|
+
expect(Size.parse(str).bytes()).toEqual(bytes);
|
|
68
|
+
} else {
|
|
69
|
+
expect(() => Size.parse(str)).toThrow();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Timer } from './timer.class';
|
|
2
|
+
import type { Timespan } from './timespan.class';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Works in the same way as setInterval. Difference is that it
|
|
6
|
+
* repeat setTimeouts behind the scenes. This gives one important
|
|
7
|
+
* advantage: executions of the callback can't overlap
|
|
8
|
+
*/
|
|
9
|
+
export const repeat = (
|
|
10
|
+
interval: Timespan,
|
|
11
|
+
fn: (timer: Timer) => void | Promise<void>,
|
|
12
|
+
): Timer => {
|
|
13
|
+
const timer = new Timer();
|
|
14
|
+
|
|
15
|
+
setTimeout(async function iteration() {
|
|
16
|
+
await fn(timer);
|
|
17
|
+
|
|
18
|
+
if (timer.isRunning) {
|
|
19
|
+
setTimeout(iteration, interval.millis());
|
|
20
|
+
}
|
|
21
|
+
}, interval.millis());
|
|
22
|
+
|
|
23
|
+
return timer;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// IDEA:
|
|
27
|
+
// Run and repeat function, when first iteration starts immediately
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
export type HrTime = [number, number];
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Timer used to mesure execution time.
|
|
5
|
+
*
|
|
6
|
+
* @export
|
|
7
|
+
* @class Stopwatch
|
|
8
|
+
*/
|
|
9
|
+
export class Stopwatch {
|
|
10
|
+
private _start: HrTime | null;
|
|
11
|
+
private _current: HrTime | null;
|
|
12
|
+
private _isRunning: boolean;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Number of milliseconds passed from stopwatch started.
|
|
16
|
+
*
|
|
17
|
+
* @readonly
|
|
18
|
+
* @type {number}
|
|
19
|
+
* @memberof Stopwatch
|
|
20
|
+
*/
|
|
21
|
+
get elapsedMilliseconds(): number {
|
|
22
|
+
return this.convertToMilliseconds(this.elapsed);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Time in process.hrtime format passed from stopwatch started.
|
|
27
|
+
*
|
|
28
|
+
* @readonly
|
|
29
|
+
* @type {HrTime}
|
|
30
|
+
* @memberof Stopwatch
|
|
31
|
+
*/
|
|
32
|
+
get elapsed(): HrTime {
|
|
33
|
+
if (!this._start || !this._current) {
|
|
34
|
+
return [0, 0];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return this._isRunning ? process.hrtime(this._start) : this._current;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Stops the stopwatch and clears time.
|
|
42
|
+
* Returns this.
|
|
43
|
+
*
|
|
44
|
+
* @returns {Stopwatch}
|
|
45
|
+
* @memberof Stopwatch
|
|
46
|
+
*/
|
|
47
|
+
reset(): Stopwatch {
|
|
48
|
+
this._start = null;
|
|
49
|
+
this._current = null;
|
|
50
|
+
this._isRunning = false;
|
|
51
|
+
|
|
52
|
+
return this;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Clears time and restarts the stopwatch.
|
|
57
|
+
* Returns this.
|
|
58
|
+
*
|
|
59
|
+
* @returns {Stopwatch}
|
|
60
|
+
* @memberof Stopwatch
|
|
61
|
+
*/
|
|
62
|
+
restart(): Stopwatch {
|
|
63
|
+
this.reset();
|
|
64
|
+
this.start();
|
|
65
|
+
|
|
66
|
+
return this;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Starts stopwatch.
|
|
71
|
+
* Returns this.
|
|
72
|
+
*
|
|
73
|
+
* @returns {Stopwatch}
|
|
74
|
+
* @memberof Stopwatch
|
|
75
|
+
*/
|
|
76
|
+
start(): Stopwatch {
|
|
77
|
+
if (!this._start) {
|
|
78
|
+
this._start = process.hrtime();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
this._isRunning = true;
|
|
82
|
+
|
|
83
|
+
return this;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Pauses stopwatch. Can be resumed with .start()
|
|
88
|
+
* Returns this.
|
|
89
|
+
*
|
|
90
|
+
* @returns {Stopwatch}
|
|
91
|
+
* @memberof Stopwatch
|
|
92
|
+
*/
|
|
93
|
+
pause(): Stopwatch {
|
|
94
|
+
if (this._start) {
|
|
95
|
+
this._current = process.hrtime(this._start);
|
|
96
|
+
this._isRunning = false;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return this;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private convertToMilliseconds(hrtime: HrTime): number {
|
|
103
|
+
const nanoseconds = hrtime[0] * 1e9 + hrtime[1];
|
|
104
|
+
const milliseconds = nanoseconds / 1e6;
|
|
105
|
+
|
|
106
|
+
return milliseconds;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Created with repeat() function it can be
|
|
3
|
+
* stopped by calling stop() method
|
|
4
|
+
*/
|
|
5
|
+
export class Timer {
|
|
6
|
+
private _isRunning = true;
|
|
7
|
+
|
|
8
|
+
get isRunning(): boolean {
|
|
9
|
+
return this._isRunning;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
stop(): void {
|
|
13
|
+
this._isRunning = false;
|
|
14
|
+
}
|
|
15
|
+
}
|