@noeldemartin/utils 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.nvmrc +1 -0
  2. package/README.md +25 -0
  3. package/dist/noeldemartin-utils.cjs.js +1 -1
  4. package/dist/noeldemartin-utils.cjs.js.map +1 -1
  5. package/dist/noeldemartin-utils.d.ts +173 -20
  6. package/dist/noeldemartin-utils.esm.js +1 -1
  7. package/dist/noeldemartin-utils.esm.js.map +1 -1
  8. package/dist/noeldemartin-utils.umd.js +1 -1
  9. package/dist/noeldemartin-utils.umd.js.map +1 -1
  10. package/package.json +11 -8
  11. package/src/fluent/FluentArray.ts +9 -2
  12. package/src/fluent/FluentObject.ts +2 -2
  13. package/src/fluent/index.ts +1 -0
  14. package/src/fluent/noop.ts +3 -0
  15. package/src/helpers/JSError.ts +25 -0
  16. package/src/helpers/MagicObject.ts +89 -0
  17. package/src/helpers/ObjectsMap.ts +18 -0
  18. package/src/helpers/PromisedValue.ts +51 -7
  19. package/src/helpers/array_helpers.ts +108 -34
  20. package/src/helpers/boolean_helpers.ts +11 -0
  21. package/src/helpers/chaos_helpers.ts +10 -0
  22. package/src/helpers/error_helpers.ts +16 -3
  23. package/src/helpers/escape_helpers.ts +7 -0
  24. package/src/helpers/file_helpers.ts +12 -0
  25. package/src/helpers/hash_helpers.ts +171 -0
  26. package/src/helpers/index.ts +16 -2
  27. package/src/helpers/location_helpers.ts +33 -0
  28. package/src/helpers/logical_helpers.ts +2 -3
  29. package/src/helpers/mixin_helpers.ts +7 -0
  30. package/src/helpers/network_helpers.ts +3 -0
  31. package/src/helpers/object_helpers.ts +18 -2
  32. package/src/helpers/promise_helpers.ts +1 -1
  33. package/src/helpers/runtime_helpers.ts +2 -1
  34. package/src/helpers/string_helpers.ts +34 -3
  35. package/src/helpers/url_helpers.ts +3 -1
  36. package/src/helpers/value_helpers.ts +7 -0
  37. package/src/testing/index.ts +5 -4
  38. package/src/testing/mocking.ts +26 -0
  39. package/src/types/arrays.ts +29 -0
  40. package/src/types/classes.ts +10 -0
  41. package/src/types/helpers.ts +14 -0
  42. package/src/types/index.ts +3 -14
  43. package/src/helpers/Error.ts +0 -17
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noeldemartin/utils",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "My JavaScript utilities",
5
5
  "main": "dist/noeldemartin-utils.cjs.js",
6
6
  "module": "dist/noeldemartin-utils.esm.js",
@@ -9,19 +9,20 @@
9
9
  "scripts": {
10
10
  "build": "rm dist -rf && npm run build:js && npm run build:types",
11
11
  "build:js": "noeldemartin-build-javascript",
12
- "build:types": "noeldemartin-build-types",
13
- "lint": "eslint src && tsc --noEmit",
12
+ "build:types": "noeldemartin-build-types && ./scripts/fix-error-types.sh",
13
+ "lint": "noeldemartin-lint src",
14
14
  "publish-next": "noeldemartin-publish-next",
15
15
  "test": "jest --verbose",
16
+ "test:summary": "jest --reporters jest-summary-reporter || exit 0",
16
17
  "test:coverage": "jest --coverage"
17
18
  },
18
- "engines": {
19
- "node": ">=12.x"
20
- },
21
19
  "repository": {
22
20
  "type": "git",
23
21
  "url": "git+https://github.com/noeldemartin/utils.git"
24
22
  },
23
+ "engines": {
24
+ "node": ">=14.x"
25
+ },
25
26
  "author": "Noel De Martin",
26
27
  "license": "MIT",
27
28
  "bugs": {
@@ -39,16 +40,18 @@
39
40
  "@babel/preset-env": "^7.12.16",
40
41
  "@babel/preset-typescript": "^7.12.16",
41
42
  "@microsoft/api-extractor": "^7.12.0",
42
- "@noeldemartin/eslint-config-typescript": "^0.1.0",
43
- "@noeldemartin/scripts": "^0.1.1",
43
+ "@noeldemartin/eslint-config-typescript": "^0.1.1",
44
+ "@noeldemartin/scripts": "^0.1.2",
44
45
  "@rollup/plugin-alias": "^3.1.2",
45
46
  "@rollup/plugin-babel": "^5.2.3",
46
47
  "@rollup/plugin-commonjs": "^17.1.0",
47
48
  "@rollup/plugin-node-resolve": "^11.1.1",
48
49
  "@rollup/plugin-typescript": "^8.1.1",
50
+ "@types/jest": "^27.0.3",
49
51
  "babel-plugin-transform-remove-imports": "^1.5.2",
50
52
  "eslint": "^7.13.0",
51
53
  "jest": "^26.6.3",
54
+ "jest-summary-reporter": "^0.0.2",
52
55
  "rollup": "^2.33.3",
53
56
  "rollup-plugin-terser": "^7.0.2",
54
57
  "ts-jest": "^26.4.4",
@@ -6,6 +6,8 @@ import {
6
6
  arrayFlatMap,
7
7
  arrayIsEmpty,
8
8
  arrayProject,
9
+ arrayRandomItem,
10
+ arrayRandomItems,
9
11
  arrayRemove,
10
12
  arrayRemoveIndex,
11
13
  arrayReplace,
@@ -31,6 +33,8 @@ const fluentArrayHelpers: FluentArrayHelpers<unknown> = {
31
33
  flatMap: arrayFlatMap,
32
34
  isEmpty: arrayIsEmpty,
33
35
  project: arrayProject,
36
+ randomItem: arrayRandomItem,
37
+ randomItems: arrayRandomItems,
34
38
  remove: arrayRemove,
35
39
  removeIndex: arrayRemoveIndex,
36
40
  replace: arrayReplace,
@@ -49,6 +53,8 @@ export type FluentArrayHelpers<T> = {
49
53
  flatMap<R>(items: T[], transformation?: (item: T, index: number) => R[]): R[];
50
54
  isEmpty(items: T[]): boolean;
51
55
  project(items: T[], property: string): unknown[];
56
+ randomItem(items: T[]): T | null;
57
+ randomItems(items: T[], count: number): T[];
52
58
  remove(items: T[], item: T): boolean;
53
59
  removeIndex(items: T[], index: number | string): boolean;
54
60
  replace(items: T[], original: T, replacement: T): boolean;
@@ -81,14 +87,15 @@ class FluentArrayDefinition<Item> extends FluentObjectDefinition<Item[]> {
81
87
  declare public flatMap: <T>(callback: (item: Item, index: number) => T[])
82
88
  => FluentArrayInstance<FluentArrayDefinition<T>, T>;
83
89
 
84
- declare public map: <T>(callback: (item: Item) => T) => FluentArrayInstance<FluentArrayDefinition<T>, T>;
90
+ declare public map: <T>(callback: (item: Item, index: number) => T)
91
+ => FluentArrayInstance<FluentArrayDefinition<T>, T>;
85
92
 
86
93
  declare public project: <K extends keyof Item>(key: K) => Item[K][];
87
94
 
88
95
  declare public where: <K extends keyof Item>(key: K, value?: Item[K]) =>
89
96
  FluentArrayInstance<FluentArrayDefinition<Item>, Item>;
90
97
 
91
- public get(index: number): Item {
98
+ public get(index: number): Item | undefined {
92
99
  return this.value[index];
93
100
  }
94
101
 
@@ -46,7 +46,7 @@ export function addHelperMethodsToPrototype(
46
46
  prototype[name] = function(...args: any[]) {
47
47
  const value = method(this.value, ...args);
48
48
 
49
- return this.chain(value);
49
+ return this.chain?.(value);
50
50
  };
51
51
  }
52
52
  }
@@ -75,7 +75,7 @@ export function addPrimitiveMethodsToPrototype(
75
75
  prototype[name] = function(...args: any[]) {
76
76
  const value = descriptor.value.call(this.value, ...args);
77
77
 
78
- return this.chain(value);
78
+ return this.chain?.(value);
79
79
  };
80
80
  }
81
81
  }
@@ -57,6 +57,7 @@ export function fluent(value: unknown): unknown {
57
57
  export { tap } from './tap';
58
58
  export type { Tapped } from './tap';
59
59
 
60
+ export { noop } from './noop';
60
61
  export { value } from './value';
61
62
  export { when } from './when';
62
63
 
@@ -0,0 +1,3 @@
1
+ export function noop(): void {
2
+ // Nothing to do here.
3
+ }
@@ -0,0 +1,25 @@
1
+ import { runtimeGlobal } from '@/helpers/runtime_helpers';
2
+ import type { ClosureArgs } from '@/types/index';
3
+
4
+ export const RuntimeErrorClass = runtimeGlobal<typeof globalThis>().Error;
5
+
6
+ export interface JSErrorOptions {
7
+ cause?: unknown;
8
+ }
9
+
10
+ export default class JSError extends RuntimeErrorClass {
11
+
12
+ declare public name: string;
13
+ declare public message: string;
14
+ declare public stack?: string;
15
+ declare public cause?: unknown;
16
+
17
+ constructor(message?: string, options?: JSErrorOptions) {
18
+ super(...[message, options] as ClosureArgs);
19
+
20
+ // Fix inheritance: https://stackoverflow.com/questions/41102060/typescript-extending-error-class
21
+ this.name = new.target.name === 'JSError' ? 'Error' : new.target.name;
22
+ Object.setPrototypeOf(this, new.target.prototype);
23
+ }
24
+
25
+ }
@@ -0,0 +1,89 @@
1
+ import type { Constructor } from '../types/classes';
2
+
3
+ export type MagicObjectConstructor<T extends MagicObject = MagicObject> = Constructor<T> & typeof MagicObject;
4
+
5
+ export default class MagicObject {
6
+
7
+ private static __buildingPureInstance: boolean;
8
+ private static __reservedProperties: WeakMap<typeof MagicObject, Set<string>> = new WeakMap;
9
+
10
+ private static buildingPureInstance(this: MagicObjectConstructor): boolean {
11
+ if (this.__buildingPureInstance)
12
+ return true;
13
+
14
+ if (this.__reservedProperties.has(this))
15
+ return false;
16
+
17
+ this.__buildingPureInstance = true;
18
+ this.__reservedProperties.set(this, new Set(Object.getOwnPropertyNames(new this)));
19
+ this.__buildingPureInstance = false;
20
+
21
+ return false;
22
+ }
23
+
24
+ protected static isReservedProperty(property: string): boolean {
25
+ return !!this.__reservedProperties.get(this)?.has(property);
26
+ }
27
+
28
+ declare protected _proxyTarget: this;
29
+ declare protected _proxy: this;
30
+
31
+ constructor() {
32
+ if (this.static().buildingPureInstance())
33
+ return;
34
+
35
+ this.initializeProxy();
36
+
37
+ return this._proxy;
38
+ }
39
+
40
+ protected static(): MagicObjectConstructor<this> {
41
+ return this.constructor as MagicObjectConstructor<this>;
42
+ }
43
+
44
+ protected __get(property: string): unknown {
45
+ return Reflect.get(this._proxyTarget, property);
46
+ }
47
+
48
+ protected __set(property: string, value: unknown): void {
49
+ Reflect.set(this._proxyTarget, property, value);
50
+ }
51
+
52
+ protected __delete(property: string): void {
53
+ Reflect.deleteProperty(this._proxyTarget, property);
54
+ }
55
+
56
+ protected initializeProxy(): void {
57
+ const Static = this.static();
58
+
59
+ this._proxyTarget = this;
60
+ this._proxy = new Proxy(this._proxyTarget, {
61
+ get(target, property, receiver) {
62
+ if (typeof property !== 'string' || property in target || Static.isReservedProperty(property)) {
63
+ return Reflect.get(target, property, receiver);
64
+ }
65
+
66
+ return target.__get(property);
67
+ },
68
+ set(target, property, value, receiver) {
69
+ if (typeof property !== 'string' || property in target || Static.isReservedProperty(property)) {
70
+ return Reflect.set(target, property, value, receiver);
71
+ }
72
+
73
+ target.__set(property, value);
74
+
75
+ return true;
76
+ },
77
+ deleteProperty(target, property) {
78
+ if (typeof property !== 'string' || property in target || Static.isReservedProperty(property)) {
79
+ return Reflect.deleteProperty(target, property);
80
+ }
81
+
82
+ target.__delete(property);
83
+
84
+ return true;
85
+ },
86
+ });
87
+ }
88
+
89
+ }
@@ -40,6 +40,10 @@ export default class ObjectsMap<Item extends object> {
40
40
  yield* this.keysToItems;
41
41
  }
42
42
 
43
+ public get size(): number {
44
+ return this.keysToItems.size;
45
+ }
46
+
43
47
  public items(): IterableIterator<Item> {
44
48
  return this.keysToItems.values();
45
49
  }
@@ -93,6 +97,20 @@ export default class ObjectsMap<Item extends object> {
93
97
  this.keysToItems.delete(key);
94
98
  }
95
99
 
100
+ public filter(condition: (item: Item, key: string) => boolean): this {
101
+ const filteredMap = (this.constructor as typeof ObjectsMap).createFromArray([], this.getKey);
102
+
103
+ for (const [key, item] of this.entries()) {
104
+ if (!condition(item, key)) {
105
+ continue;
106
+ }
107
+
108
+ filteredMap.add(item);
109
+ }
110
+
111
+ return filteredMap as this;
112
+ }
113
+
96
114
  public clear(): void {
97
115
  this.itemsToKeys = new WeakMap();
98
116
  this.keysToItems.clear();
@@ -1,3 +1,9 @@
1
+ import { arrayRemove } from './array_helpers';
2
+
3
+ export type PromisedValueResolveListener<T> = (result: T) => unknown;
4
+ export type PromisedValueRejectListener = (reason?: Error) => unknown;
5
+ export type PromisedValueResetListener = () => unknown;
6
+
1
7
  export default class PromisedValue<T = unknown> implements Promise<T> {
2
8
 
3
9
  public static from<T>(promise: Promise<T>): PromisedValue<T> {
@@ -10,16 +16,20 @@ export default class PromisedValue<T = unknown> implements Promise<T> {
10
16
  return promisedValue;
11
17
  }
12
18
 
13
- private _value?: T;
19
+ declare private _value?: T;
14
20
  declare private promise: Promise<T>;
15
21
  declare private _resolve: (result: T) => void;
16
- declare private _reject: (error?: Error) => void;
22
+ declare private _reject: (reason?: Error) => void;
23
+
24
+ private resolveListeners: PromisedValueResolveListener<T>[] = [];
25
+ private rejectListeners: PromisedValueRejectListener[] = [];
26
+ private resetListeners: PromisedValueResetListener[] = [];
17
27
 
18
28
  constructor() {
19
- this.initPromise();
29
+ this.setPromiseValues();
20
30
  }
21
31
 
22
- public [Symbol.toStringTag]: string;
32
+ declare public [Symbol.toStringTag]: string;
23
33
 
24
34
  public get value(): T | null {
25
35
  return this._value || null;
@@ -47,18 +57,52 @@ export default class PromisedValue<T = unknown> implements Promise<T> {
47
57
  }
48
58
 
49
59
  public resolve(value: T): void {
50
- if (this.isResolved())
51
- this.initPromise();
60
+ if (this.isResolved()) {
61
+ this.reset();
62
+ }
52
63
 
53
64
  this._value = value;
54
65
  this._resolve(value);
66
+
67
+ this.resolveListeners.forEach(listener => listener(value));
55
68
  }
56
69
 
57
70
  public reject(reason?: Error): void {
71
+ if (this.isResolved()) {
72
+ this.reset();
73
+ }
74
+
75
+ delete this._value;
58
76
  this._reject(reason);
77
+
78
+ this.rejectListeners.forEach(listener => listener(reason));
79
+ }
80
+
81
+ public onResolve(listener: PromisedValueResolveListener<T>): () => void {
82
+ this.resolveListeners.push(listener);
83
+
84
+ return () => arrayRemove(this.resolveListeners, listener);
85
+ }
86
+
87
+ public onReject(listener: PromisedValueRejectListener): () => void {
88
+ this.rejectListeners.push(listener);
89
+
90
+ return () => arrayRemove(this.rejectListeners, listener);
91
+ }
92
+
93
+ public onReset(listener: PromisedValueResetListener): () => void {
94
+ this.resetListeners.push(listener);
95
+
96
+ return () => arrayRemove(this.resetListeners, listener);
97
+ }
98
+
99
+ public reset(): void {
100
+ this.setPromiseValues();
101
+
102
+ this.rejectListeners.forEach(listener => listener());
59
103
  }
60
104
 
61
- private initPromise(): void {
105
+ private setPromiseValues(): void {
62
106
  this.promise = new Promise((resolve, reject) => {
63
107
  this._resolve = resolve;
64
108
  this._reject = reject;
@@ -1,4 +1,4 @@
1
- import type { Falsy } from '@/types/index';
1
+ import type { Closure, Falsy } from '@/types/index';
2
2
 
3
3
  import { compare } from './logical_helpers';
4
4
  import { isIterable, isString } from './object_helpers';
@@ -7,12 +7,19 @@ export function arrayClear(items: unknown[]): void {
7
7
  items.splice(0, items.length);
8
8
  }
9
9
 
10
- export function arrayDiff<T>(original: T[], updated: T[]): { added: T[]; removed: T[] } {
10
+ export function arrayDiff<T>(
11
+ original: T[],
12
+ updated: T[],
13
+ compare?: (a: T, b: T) => boolean,
14
+ ): { added: T[]; removed: T[] } {
11
15
  const removed = original.slice(0);
12
16
  const added = [];
17
+ const search: ((item: T, items: T[]) => number) = compare
18
+ ? (item, items) => items.findIndex(otherItem => compare(item, otherItem))
19
+ : (item, items) => items.indexOf(item);
13
20
 
14
21
  for (const updatedItem of updated) {
15
- const index = removed.indexOf(updatedItem);
22
+ const index = search(updatedItem, removed);
16
23
 
17
24
  index !== -1
18
25
  ? removed.splice(index, 1)
@@ -32,6 +39,14 @@ export function arrayChunk<T>(items: T[], chunkSize: number): T[][] {
32
39
  return chunks;
33
40
  }
34
41
 
42
+ export function arrayEquals<T>(original: T[], updated: T[]): boolean {
43
+ if (original.length !== updated.length) {
44
+ return false;
45
+ }
46
+
47
+ return !original.some((value, index) => updated[index] !== value);
48
+ }
49
+
35
50
  export function arrayFilter<T>(items: T[]): Exclude<T, Falsy>[];
36
51
  export function arrayFilter<T>(items: T[], filter: (item: T) => boolean): T[];
37
52
  export function arrayFilter<T>(items: T[], filter?: (item: T) => boolean): T[] {
@@ -55,6 +70,14 @@ export function arrayFlatMap<T, R>(items: T[], transformation: (item: T, index:
55
70
  return [...items.entries()].flatMap(([index, item]) => transformation(item, index));
56
71
  }
57
72
 
73
+ export function arrayWithItemAt<T>(items: T[], item: T, index: number): T[] {
74
+ return [
75
+ ...items.slice(0, index + 1),
76
+ item,
77
+ ...items.slice(index + 1),
78
+ ];
79
+ }
80
+
58
81
  export function arrayIsEmpty(items: unknown[]): boolean {
59
82
  return items.length === 0;
60
83
  }
@@ -63,7 +86,7 @@ export function arrayProject<T, S extends keyof T>(items: T[], property: S): T[S
63
86
  return items.map(item => item[property]);
64
87
  }
65
88
 
66
- export function arrayPull<T>(items: T[], index: number): T {
89
+ export function arrayPull<T>(items: T[], index: number): T | undefined {
67
90
  const value = items[index];
68
91
 
69
92
  items.splice(index, 1);
@@ -71,6 +94,26 @@ export function arrayPull<T>(items: T[], index: number): T {
71
94
  return value;
72
95
  }
73
96
 
97
+ export function arrayRandomItem<T>(items: T[]): T | null {
98
+ return items.length === 0
99
+ ? null
100
+ : items[Math.floor(Math.random() * items.length)] as T;
101
+ }
102
+
103
+ export function arrayRandomItems<T>(items: T[], count: number): T[] {
104
+ const itemsLeft = items.slice(0);
105
+ const randomItems = [] as T[];
106
+
107
+ while (itemsLeft.length > 0 && randomItems.length < count) {
108
+ const index = Math.floor(Math.random() * itemsLeft.length);
109
+
110
+ randomItems.push(itemsLeft[index] as T);
111
+ itemsLeft.splice(index, 1);
112
+ }
113
+
114
+ return randomItems;
115
+ }
116
+
74
117
  export function arrayRemove<T>(items: T[], item: T): boolean {
75
118
  const index = items.indexOf(item);
76
119
 
@@ -98,24 +141,57 @@ export function arrayReplace<T>(items: T[], original: T, replacement: T): boolea
98
141
  }
99
142
 
100
143
  export function arraySorted<T>(items: T[]): T[];
101
- export function arraySorted<T>(items: T[], compare?: (a: T, b: T) => number): T[];
102
- export function arraySorted<T>(items: T[], field?: keyof T, direction?: 'asc' | 'desc'): T[];
144
+ export function arraySorted<T>(items: T[], direction: 'asc' | 'desc'): T[];
145
+ export function arraySorted<T>(items: T[], compare: (a: T, b: T) => number): T[];
146
+ export function arraySorted<T>(items: T[], field: keyof T, direction?: 'asc' | 'desc'): T[];
147
+ export function arraySorted<T>(items: T[], fields: (keyof T)[], direction?: 'asc' | 'desc'): T[];
103
148
  export function arraySorted<T>(
104
149
  items: T[],
105
- compareOrField?: keyof T | ((a: T, b: T) => number),
150
+ compareOrFieldOrDirection?: keyof T | (keyof T)[] | ((a: T, b: T) => number) | 'asc' | 'desc',
106
151
  direction?: 'asc' | 'desc',
107
152
  ): T[] {
108
- const comparisonFn = typeof compareOrField !== 'string'
109
- ? compareOrField as undefined | ((a: T, b: T) => number)
110
- : direction === 'desc'
111
- ? (a: T, b: T) => compare(b[compareOrField], a[compareOrField])
112
- : (a: T, b: T) => compare(a[compareOrField], b[compareOrField]);
113
-
114
- const sorted = items.slice(0);
115
-
116
- sorted.sort(comparisonFn);
153
+ direction = compareOrFieldOrDirection === 'asc' || compareOrFieldOrDirection === 'desc'
154
+ ? compareOrFieldOrDirection as 'asc' | 'desc'
155
+ : direction;
156
+
157
+ const getComparisonFunction = (): Closure<[T, T], number> | undefined => {
158
+ const compareItems = direction === 'desc'
159
+ ? (field: keyof T) => (a: T, b: T) => compare(b[field], a[field])
160
+ : (field: keyof T) => (a: T, b: T) => compare(a[field], b[field]);
161
+
162
+ switch (typeof compareOrFieldOrDirection) {
163
+ case 'function':
164
+ return compareOrFieldOrDirection;
165
+ case 'string':
166
+ if (compareOrFieldOrDirection === 'asc')
167
+ return;
168
+
169
+ if (compareOrFieldOrDirection === 'desc')
170
+ return (a, b) => compare(b, a);
171
+
172
+ return compareItems(compareOrFieldOrDirection);
173
+ case 'object': {
174
+ const comparisonFunctions = compareOrFieldOrDirection.map(field => compareItems(field));
175
+
176
+ return (a: T, b: T) => {
177
+ for (const comparisonFunction of comparisonFunctions) {
178
+ const result = comparisonFunction(a, b);
179
+
180
+ if (result !== 0)
181
+ return result;
182
+ }
183
+
184
+ return 0;
185
+ };
186
+ }
187
+ }
188
+ };
189
+
190
+ return items.slice(0).sort(getComparisonFunction());
191
+ }
117
192
 
118
- return sorted;
193
+ export function arraySwap(items: unknown[], firstIndex: number, secondIndex: number): void {
194
+ [items[firstIndex], items[secondIndex]] = [items[secondIndex], items[firstIndex]];
119
195
  }
120
196
 
121
197
  export function arrayUnique<T>(items: T[], extractKey?: (item: T) => string): T[] {
@@ -141,8 +217,14 @@ export function arrayWhere<T, K extends keyof T>(items: T[], filter: string, val
141
217
  });
142
218
  }
143
219
 
144
- export function arrayWithout<T>(items: T[], exclude: T[]): T[] {
145
- return arrayFilter(items, item => exclude.indexOf(item) === -1);
220
+ export function arrayWithout<T>(items: T[], exclude: T | T[]): T[] {
221
+ return Array.isArray(exclude)
222
+ ? arrayFilter(items, item => exclude.indexOf(item) === -1)
223
+ : arrayWithoutIndex(items, items.indexOf(exclude));
224
+ }
225
+
226
+ export function arrayWithoutIndex<T>(items: T[], index: number): T[] {
227
+ return arrayWithoutIndexes(items, [index]);
146
228
  }
147
229
 
148
230
  export function arrayWithoutIndexes<T>(items: T[], indexes: number[]): T[] {
@@ -154,9 +236,10 @@ export function arrayWithoutIndexes<T>(items: T[], indexes: number[]): T[] {
154
236
 
155
237
  export function arrayZip<T>(...arrays: T[][]): T[][] {
156
238
  const zippedArrays: T[][] = [];
239
+ const arraysLength = arrays[0]?.length ?? 0;
157
240
 
158
- for (let i = 0; i < arrays[0].length; i++)
159
- zippedArrays.push(arrays.map(a => a[i]));
241
+ for (let i = 0; i < arraysLength; i++)
242
+ zippedArrays.push(arrays.map(a => a[i] as T));
160
243
 
161
244
  return zippedArrays;
162
245
  }
@@ -164,20 +247,11 @@ export function arrayZip<T>(...arrays: T[][]): T[][] {
164
247
  export function arrayFrom<T>(value: Iterable<T>): T[];
165
248
  export function arrayFrom<T>(value: T): T[];
166
249
  export function arrayFrom(value: unknown): unknown[] {
167
- if (Array.isArray(value))
168
- return value.slice(0);
169
-
170
- if (isIterable(value) && !isString(value))
171
- return [...value];
172
-
173
- return [value];
250
+ return Array.isArray(value) || (isIterable(value) && !isString(value))
251
+ ? Array.from(value)
252
+ : [value];
174
253
  }
175
254
 
176
255
  export function range(length: number): number[] {
177
- const items: number[] = [];
178
-
179
- for (let i = 0; i < length; i++)
180
- items.push(i);
181
-
182
- return items;
256
+ return Array.from({ length }, (_, item) => item);
183
257
  }
@@ -0,0 +1,11 @@
1
+ export function parseBoolean(value: unknown): boolean {
2
+ if (!value) {
3
+ return false;
4
+ }
5
+
6
+ if ((['0', 'false'] as unknown[]).includes(value)) {
7
+ return false;
8
+ }
9
+
10
+ return true;
11
+ }
@@ -0,0 +1,10 @@
1
+ export function randomInt(): number;
2
+ export function randomInt(max: number): number;
3
+ export function randomInt(min: number, max: number): number;
4
+ export function randomInt(minOrMax?: number, max?: number): number {
5
+ const maxProvided = typeof max === 'number';
6
+ const min = maxProvided ? minOrMax as number : 0;
7
+ max = maxProvided ? max as number : (minOrMax ?? Number.MAX_SAFE_INTEGER);
8
+
9
+ return Math.round(Math.random() * (max - min) + min);
10
+ }
@@ -1,18 +1,31 @@
1
1
  import type { Constructor } from '@/types/index';
2
2
 
3
+ import { evaluate } from './value_helpers';
4
+ import type JSError from './JSError';
5
+ import type { EvaluatesTo } from './value_helpers';
6
+
7
+ /* eslint-disable @typescript-eslint/no-explicit-any, max-len */
8
+ export function assert(assertion: EvaluatesTo<boolean>, message?: string): void;
9
+ export function assert<E extends Error = Error>(assertion: EvaluatesTo<boolean>, errorClass?: Constructor<E>, ...params: ConstructorParameters<Constructor<E>>): void;
10
+ export function assert(assertion: EvaluatesTo<boolean>, messageOrClass?: string | Constructor<Error>, ...params: any[]): void {
11
+ evaluate(assertion) || fail(messageOrClass as any, ...params);
12
+ }
13
+ /* eslint-enable @typescript-eslint/no-explicit-any, max-len */
14
+
3
15
  export function catchError(callback: () => unknown): Error | null {
4
16
  try {
5
17
  callback();
6
18
 
7
19
  return null;
8
20
  } catch (error) {
9
- return error;
21
+ return error as Error;
10
22
  }
11
23
  }
12
24
 
13
25
  /* eslint-disable @typescript-eslint/no-explicit-any, max-len */
14
- export function fail(message?: string): any;
15
- export function fail<T extends Error>(errorClass?: Constructor<T>, ...params: ConstructorParameters<Constructor<T>>): any;
26
+ export function fail<T = any>(message?: string): T;
27
+ export function fail<T = any, E extends Error = Error>(errorClass?: Constructor<E>, ...params: ConstructorParameters<Constructor<E>>): T;
28
+ export function fail<T = any, E extends JSError = JSError>(errorClass?: Constructor<E>, ...params: ConstructorParameters<Constructor<E>>): T;
16
29
  export function fail(messageOrClass: string | Constructor<Error> = 'Something went wrong', ...params: any[]): any {
17
30
  const errorClass = typeof messageOrClass === 'string' ? Error : messageOrClass;
18
31
 
@@ -0,0 +1,7 @@
1
+ export function escapeHtmlEntities(text: string): string {
2
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3
+ }
4
+
5
+ export function escapeRegexText(text: string): string {
6
+ return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
7
+ }
@@ -0,0 +1,12 @@
1
+ export function downloadFile(filename: string, content: string, mediaType: string): void {
2
+ const url = window.URL.createObjectURL(new Blob([content], { type: mediaType }));
3
+ const anchor = document.createElement('a');
4
+
5
+ anchor.style.display = 'none';
6
+ anchor.href = url;
7
+ anchor.download = filename;
8
+ document.body.appendChild(anchor);
9
+ anchor.click();
10
+ window.URL.revokeObjectURL(url);
11
+ document.body.removeChild(anchor);
12
+ }