@inrixia/helpers 2.0.5 → 2.0.6

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 (53) hide show
  1. package/dist/conv.d.ts +28 -0
  2. package/dist/conv.d.ts.map +1 -0
  3. package/{src/conv.ts → dist/conv.js} +13 -15
  4. package/dist/conv.js.map +1 -0
  5. package/dist/geo.d.ts +19 -0
  6. package/dist/geo.d.ts.map +1 -0
  7. package/dist/geo.js +32 -0
  8. package/dist/geo.js.map +1 -0
  9. package/dist/index.d.ts +9 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/{src/index.ts → dist/index.js} +9 -8
  12. package/dist/index.js.map +1 -0
  13. package/dist/logic.d.ts +23 -0
  14. package/dist/logic.d.ts.map +1 -0
  15. package/dist/logic.js +50 -0
  16. package/dist/logic.js.map +1 -0
  17. package/dist/math.d.ts +35 -0
  18. package/dist/math.d.ts.map +1 -0
  19. package/{src/math.ts → dist/math.js} +19 -20
  20. package/dist/math.js.map +1 -0
  21. package/dist/object.d.ts +169 -0
  22. package/dist/object.d.ts.map +1 -0
  23. package/dist/object.js +349 -0
  24. package/dist/object.js.map +1 -0
  25. package/dist/react.d.ts +2 -0
  26. package/dist/react.d.ts.map +1 -0
  27. package/dist/react.js +14 -0
  28. package/dist/react.js.map +1 -0
  29. package/dist/test.d.ts +27 -0
  30. package/dist/test.d.ts.map +1 -0
  31. package/dist/test.js +69 -0
  32. package/dist/test.js.map +1 -0
  33. package/dist/ts/math.d.ts +12 -0
  34. package/dist/ts/math.d.ts.map +1 -0
  35. package/dist/ts/math.js +2 -0
  36. package/dist/ts/math.js.map +1 -0
  37. package/dist/ts/numRange.d.ts +12 -0
  38. package/dist/ts/numRange.d.ts.map +1 -0
  39. package/dist/ts/numRange.js +2 -0
  40. package/dist/ts/numRange.js.map +1 -0
  41. package/dist/ts.d.ts +29 -0
  42. package/dist/ts.d.ts.map +1 -0
  43. package/dist/ts.js +6 -0
  44. package/dist/ts.js.map +1 -0
  45. package/package.json +1 -1
  46. package/src/geo.ts +0 -33
  47. package/src/logic.ts +0 -52
  48. package/src/object.ts +0 -349
  49. package/src/react.ts +0 -11
  50. package/src/test.ts +0 -86
  51. package/src/ts/math.ts +0 -62
  52. package/src/ts/numRange.ts +0 -15
  53. package/src/ts.ts +0 -54
package/src/geo.ts DELETED
@@ -1,33 +0,0 @@
1
- /**
2
- * Converts latitude or longitude to degrees, minutes & seconds.
3
- * @param coord Latitude or longitude coordinate
4
- *
5
- * @returns Coordinate in degrees, minutes & seconds
6
- */
7
- export const toDMS = (coord: number): { degrees: number; minutes: number; seconds: number } => {
8
- const absolute = Math.abs(coord);
9
- const degrees = Math.floor(absolute);
10
- const minutesNotTruncated = (absolute - degrees) * 60;
11
- const minutes = Math.floor(minutesNotTruncated);
12
- const seconds = Math.floor((minutesNotTruncated - minutes) * 60);
13
- return { degrees, minutes, seconds };
14
- };
15
-
16
- // Converts numeric degrees to radians
17
- export const toRad = (val: number): number => (val * Math.PI) / 180;
18
-
19
- /**
20
- * Returns the distance between two LatLong's in kilometers
21
- * @param pos1 [lat, long] coordinates
22
- * @param pos2 [lat, long] coordinates
23
- */
24
- export const getDistance = (pos1: [number, number], pos2: [number, number]): number => {
25
- const [lat1, lon1] = pos1;
26
- const [lat2, lon2] = pos2;
27
- const R = 6371; // km
28
- const dLat = toRad(lat2 - lat1);
29
- const dLon = toRad(lon2 - lon1);
30
- const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(toRad(lat1)) * Math.cos(toRad(lat2));
31
- const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
32
- return R * c;
33
- };
package/src/logic.ts DELETED
@@ -1,52 +0,0 @@
1
- import { promisify } from "util";
2
- export const sleep = promisify(setTimeout);
3
-
4
- export class Promize<T> {
5
- public p!: Promise<T>;
6
- res!: (value: T) => void;
7
- rej!: (reason?: any) => void;
8
-
9
- /**
10
- * Returns a new instance of a `Promize`, a externally resolvable Promise.
11
- * @param resValue If not undefined, resolves the internal promise with given value on creation.
12
- */
13
- constructor(resValue?: T) {
14
- this.set(resValue);
15
- }
16
-
17
- /**
18
- * Recreate the promise
19
- * @param resValue If not undefined, resolves the internal promise with given value on creation.
20
- */
21
- set(resValue?: T): void {
22
- this.p = new Promise<T>((res, rej) => {
23
- this.res = res;
24
- this.rej = rej;
25
- });
26
- if (resValue !== undefined) this.res(resValue);
27
- }
28
- }
29
-
30
- export const retry = <T>(
31
- func: () => Promise<T> | T,
32
- options?: { onErr?: (error: unknown, retryCount: number) => void; timeoutMultiplier?: number; maxRetries?: number }
33
- ): (() => Promise<T>) => {
34
- let retryCount = 0;
35
- const maxRetries = options?.maxRetries ?? 10;
36
- const timeoutMultiplier = options?.timeoutMultiplier ?? 1000;
37
- const onErr = options?.onErr;
38
- const tryAgain = async (): Promise<T> => {
39
- try {
40
- return await func();
41
- } catch (e) {
42
- if (onErr !== undefined) onErr(e, retryCount);
43
- if (retryCount < maxRetries) {
44
- retryCount++;
45
- if (timeoutMultiplier > 0) await sleep(Math.random() * timeoutMultiplier);
46
- return tryAgain();
47
- }
48
- throw e;
49
- }
50
- };
51
- return tryAgain;
52
- };
package/src/object.ts DELETED
@@ -1,349 +0,0 @@
1
- import util from "util";
2
- import { UnknownRecord } from "./ts.js";
3
-
4
- /**
5
- * Checks if `key` has been seen before.
6
- */
7
- const hash = new Map();
8
- export const isDuplicate = (key: unknown): boolean => {
9
- if (!hash.has(key)) hash.set(key, true);
10
- else return true;
11
- return false;
12
- };
13
-
14
- /**
15
- * Simple object check.
16
- * @param item
17
- * @returns {boolean}
18
- */
19
- export const isObject = (item: unknown): item is UnknownRecord => item !== undefined && typeof item === "object" && !Array.isArray(item);
20
-
21
- /**
22
- * Deep merge objects into target. Without modifying target.
23
- * @param target
24
- * @param source
25
- */
26
- export const deepMerge = <T extends S, S extends UnknownRecord = Partial<T>>(target: T, source: S): T & S => {
27
- const output = Object.assign({}, target);
28
- if (isObject(target) && isObject(source)) {
29
- Object.keys(source).forEach((key) => {
30
- if (isObject(source[key])) {
31
- if (!(key in target)) Object.assign(output, { [key]: source[key] });
32
- else (<UnknownRecord>output)[key] = deepMerge(<UnknownRecord>target[key], <UnknownRecord>source[key]);
33
- } else Object.assign(output, { [key]: source[key] });
34
- });
35
- }
36
- return output;
37
- };
38
-
39
- export type Types = { [key: string]: string | string[] | Types | Types[] };
40
- export type TypeCompareResult = boolean | { expectedType: string; received: string; location: string };
41
-
42
- /**
43
- * Take in a target `object` and a `types` object with identical keys but values as array of types those keys should be.
44
- * @param target Object
45
- * @param types Object identical to `target` but values are types
46
- * @returns `object` if the types dont match. `True` if they do.
47
- */
48
- export const deepTypeCompare = (target: UnknownRecord, types: Types, location = "target"): TypeCompareResult => {
49
- if (!(isObject(target) && isObject(types))) return { location, expectedType: "object", received: `${target}:${type(target)}` };
50
- for (const key in target) {
51
- const targetValue = target[key];
52
- if (isObject(targetValue)) {
53
- // If target.property is a object then check its child properties
54
- const same = deepTypeCompare(targetValue, types[key] as Types, `${location}.${key}`);
55
- if (same !== true) return same;
56
- } else {
57
- if (Array.isArray(targetValue) && Array.isArray(types[key])) {
58
- // target.property and types.property are arrays
59
- // Check each item in target.property against types.property[0]
60
- const childCheckType = types[key];
61
- for (const targetItem of targetValue) {
62
- const targetType = type(targetItem);
63
- // If the array entry is a object then check it
64
- if (targetType === "object") return deepTypeCompare(targetItem, <Types>childCheckType, `${location}.${key}`);
65
- else return compareTwo(<string | string[]>childCheckType, targetItem, `${location}.${key}`);
66
- }
67
- } else {
68
- const same = compareTwo(<string | string[]>types[key], target[key], `${location}.${key}`);
69
- if (same !== true) return same;
70
- }
71
- }
72
- }
73
- return true;
74
- };
75
-
76
- /**
77
- * Helper function for `deepTypeCompare` to compare a item to a type or set of types.
78
- * @param expectedTypes Expected type/types
79
- * @param receivedValue Object given
80
- * @param location Location of `got` given
81
- */
82
- export const compareTwo = (expectedTypes: string | string[], receivedValue: unknown, location: string): TypeCompareResult => {
83
- if (!Array.isArray(expectedTypes)) expectedTypes = [expectedTypes];
84
- const gotType = type(receivedValue);
85
- for (const expectedType of expectedTypes) {
86
- if (gotType !== expectedType) return { location, expectedType, received: `${receivedValue}:${gotType}` };
87
- }
88
- return true;
89
- };
90
-
91
- /**
92
- * Returns the type of `item` respecting `Array`, `null` and `undefined` unlike typeof.
93
- * @param item
94
- * @returns Type of item
95
- */
96
- export const type = (item: unknown): string => {
97
- if (Array.isArray(item)) return "array";
98
- if (item === null) return "null";
99
- if (item === undefined) return "undefined";
100
- return typeof item;
101
- };
102
-
103
- /**
104
- * Breaks `array` into smaller chunks based on `chunkSize`
105
- * @param array Array to break up.
106
- * @param chunkSize Maximum size of array chunks.
107
- *
108
- * @returns Array containing array chunks.
109
- */
110
- export const chunkArray = <T extends unknown[] | string>(array: T, chunkSize: number): T[] => {
111
- if (array.length < chunkSize) return [array];
112
- let i, j;
113
- const returnArray: T[] = [];
114
- for (i = 0, j = array.length; i < j; i += chunkSize) returnArray.push(array.slice(i, i + chunkSize) as T);
115
- return returnArray;
116
- };
117
-
118
- /**
119
- * stringifies and then parses a object to convert it to a JSON supported object.
120
- * @param obj Object to convert.
121
- * @example
122
- * const obj = {
123
- * a: 1,
124
- * b: [2, 7]
125
- * }
126
- * const a = objectify(obj)
127
- * const b = JSON.parse(JSON.stringify(obj))
128
- * console.log(a == b) -> true
129
- */
130
- export const objectify = (obj: UnknownRecord): UnknownRecord => JSON.parse(JSON.stringify(obj));
131
-
132
- type InspectOptions = [showHidden?: boolean, depth?: number, color?: boolean];
133
-
134
- /**
135
- * Logs a inspected object to console
136
- * @param obj Object to inspect
137
- * @param options.showHidden Show hidden properties of object
138
- * @param options.depth Depth to inspect object
139
- * @param options.color Color resulting output
140
- */
141
- export const lObj = (obj: unknown, ...options: InspectOptions): void => console.log(iObj(obj, ...options));
142
-
143
- /**
144
- * Inspects a object
145
- * @param obj Object to inspect
146
- * @param options.showHidden Show hidden properties of object
147
- * @param options.depth Depth to inspect object
148
- * @param options.color Color resulting output
149
- */
150
- export const iObj = (obj: unknown, ...options: InspectOptions): string => {
151
- if (options[0] === undefined || options[0] === null) options[0] = false;
152
- if (options[1] === undefined || options[1] === null) options[1] = 5;
153
- if (options[2] === undefined || options[2] === null) options[2] = true;
154
- return util.inspect(obj, ...options);
155
- };
156
-
157
- /**
158
- * Single line inspect object.
159
- * @param obj Object to inspect
160
- * @param options.showHidden Show hidden properties of object
161
- * @param options.depth Depth to inspect object
162
- * @param options.color Color resulting output
163
- */
164
- export const sliObj = (obj: unknown, ...options: InspectOptions): string =>
165
- iObj(obj, ...options)
166
- .replace(/\r?\n/g, " ")
167
- .replace(/ +/g, " ");
168
-
169
- type AsyncFunction = (...args: unknown[]) => Promise<unknown>;
170
- type ErrorHandler = (err: Error) => Promise<void>;
171
-
172
- /**
173
- * Recursively runs `func` and handles errors with `errorHandler` until `func` successfully finishes.
174
- * @param func Function to execute
175
- * @param errorHandler Function to execute when a error occours
176
- * @returns Return value of `func` on success
177
- */
178
- export const loopError = <F extends AsyncFunction>(func: F, errorHandler: ErrorHandler = (err: Error) => new Promise((_res, r) => r(err))): ReturnType<F> =>
179
- new Promise((resolve) => {
180
- func()
181
- .then(resolve)
182
- .catch(async (err) => {
183
- errorHandler(err).then(() => resolve(loopError(func, errorHandler)));
184
- });
185
- }) as ReturnType<F>;
186
-
187
- /**
188
- * @param array
189
- * @returns string containing ranges of numbers.
190
- * @example
191
- * const range = toRange([1, 2, 3, 12, 6,7, 5, 27, 28, 29, 40, 41, 25, 42, 12])
192
- * // range = "1-3 & 5-7 & 12 & 25 & 27-29 & 40-42"
193
- */
194
- export const toRange = (array: number[]): string => {
195
- array = array
196
- .filter((a, pos) => array.indexOf(a) === pos)
197
- .sort((a, b) => a - b)
198
- .map((a) => +a);
199
- let sum = `${array[0]}`;
200
- let lastValue = array[0];
201
- for (let i = 1; i <= array.length; i++) {
202
- if (!(array[i] - 1 === array[i - 1])) {
203
- if (array[i - 1] !== lastValue) sum += `-${array[i - 1]}`;
204
- if (array[i] !== undefined) sum += ` & ${array[i]}`;
205
- lastValue = array[i];
206
- }
207
- }
208
- return sum;
209
- };
210
-
211
- /**
212
- * Returns the `property` requested from `obj`
213
- * @param obj
214
- * @param property
215
- * @param delimiter
216
- * @example
217
- * const object = {
218
- * a: {
219
- * child: "Hello World"
220
- * }
221
- * }
222
- * const wantedProperty = "a.child"
223
- * console.log(deepGet(object, wantedProperty)) // -> "Hello World"
224
- */
225
- export const deepGet = <T = unknown>(obj: UnknownRecord, property: string, delimiter = "."): T | undefined => {
226
- const arr = property.split(delimiter);
227
- while (arr.length && (obj = obj[arr.shift() as string] as UnknownRecord));
228
- return obj as T;
229
- };
230
-
231
- type ContentTemplate = { [key: string]: string | ContentTemplate };
232
-
233
- /**
234
- * Replaces values in a given `templatestring` with contentKeys from a given `contentKeys` object.
235
- * @param contentKeys Object containing key value pairs of contentKeys to fill template string with
236
- * @param templatestring string containing templates to fill
237
- * @example
238
- * const contentKeys = {
239
- * "title": "This is a title",
240
- * "info": {
241
- * "desc": "This is some info!"
242
- * }
243
- * }
244
- * const template = "Wow! {title}... Here is some info: {info.desc}"
245
- *
246
- * fillTemplate(contentKeys, template) // => Wow! This is a title... Here is some info: This is some info!"
247
- */
248
- export const fillTemplate = (contentKeys: ContentTemplate, templatestring: string, parent = ""): string => {
249
- for (const key in contentKeys) {
250
- if (isObject(contentKeys[key])) templatestring = fillTemplate(contentKeys[key] as ContentTemplate, templatestring, `${parent}${key}.`);
251
- else templatestring = templatestring.replace(new RegExp(`{${parent}${key}}`, "g"), contentKeys[key] as string);
252
- }
253
- return templatestring;
254
- };
255
-
256
- type EnvDict = { [key: string]: string | EnvDict };
257
-
258
- /**
259
- * Converts process.env variables into a object
260
- * @example process.env["some_subproperty"] = "hello"
261
- * returns { some: { subProperty: "hello" } }
262
- */
263
- export const getEnv = (): EnvDict => {
264
- // Define our return object env variables are applied to.
265
- const envObject = {} as EnvDict;
266
- // Iterate over env keys
267
- for (const envKey in process.env) {
268
- // Set our reference object to be equal to the envObject to begin with.
269
- let objRef = envObject;
270
- // Reference to parent object to allow reassigning values that should be objects.
271
- let pObjRef: [UnknownRecord, string] | undefined = undefined;
272
- // Break apart the envKey into its keys. Ex some_subProperty = ["some", "subProperty"]
273
- // This regex handles cases where _ is in the key, it only matches the first _ per key allowing for keys with one or more _ in them
274
- const keys = envKey.split(/(?<=[^__])_/g);
275
- // For every key except the last...
276
- for (let i = 0; i < keys.length - 1; i++) {
277
- // Set the key on the objRef to a empty object if its undefined.
278
- if (!isObject(objRef)) {
279
- // If objRef is not a object. Use the parent object to set it to a object containing itself as _.
280
- if (pObjRef !== undefined) objRef = pObjRef[0][pObjRef[1]] = { _: objRef };
281
- pObjRef = [objRef, keys[i]];
282
- } else {
283
- pObjRef = [objRef, keys[i]];
284
- objRef = <EnvDict>(objRef[keys[i]] ??= {});
285
- }
286
- }
287
- // Set the last key to equal the original value
288
- // If objRef is not a object. Use the parent object to set it to a object containing itself as _.
289
- if (!isObject(objRef) && pObjRef !== undefined) objRef = pObjRef[0][pObjRef[1]] = { _: objRef };
290
- const envValue = process.env[envKey];
291
- if (envValue !== undefined) objRef[keys[keys.length - 1]] = envValue;
292
- }
293
- return <EnvDict>envObject;
294
- };
295
-
296
- type RecursiveUpdateOptions = { setUndefined?: boolean; setDefined?: boolean };
297
-
298
- /**
299
- * Recursively update properties of a object with another.
300
- * @param targetObject Object to update.
301
- * @param newObject Object with new values to write to `targetObject`.
302
- * @param options.setUndefined Defaults to `true` Set properties that are undefined on `targetObject`.
303
- * @param options.setDefined Defaults to `false`. Overwrite properties that are not undefined on `targetObject`.
304
- */
305
- export const recursiveUpdate = (
306
- targetObject: UnknownRecord,
307
- newObject: UnknownRecord,
308
- options: RecursiveUpdateOptions = { setUndefined: true, setDefined: false }
309
- ): void => {
310
- if (!isObject(targetObject)) throw new Error("targetObject is not an object!");
311
- if (!isObject(newObject)) throw new Error("newObject is not an object!");
312
- for (const key in newObject) {
313
- if (isObject(targetObject[key]) && isObject(newObject[key])) recursiveUpdate(<UnknownRecord>targetObject[key], <UnknownRecord>newObject[key], options);
314
- else if (options.setUndefined && targetObject[key] === undefined) targetObject[key] = newObject[key];
315
- else if (options.setDefined && targetObject[key] !== undefined) targetObject[key] = newObject[key];
316
- }
317
- };
318
-
319
- /**
320
- * Set the types of a given `object` based on the types of an identical `types` object. Usful in conjunction with `getEnv` to convert a object only containing strings/objects to actual types.
321
- */
322
- export const rebuildTypes = (object: UnknownRecord, types: UnknownRecord): void => {
323
- for (const key in object) {
324
- if (types[key] === undefined) continue;
325
- switch (typeof types[key]) {
326
- case "number":
327
- (<number>object[key]) = +(<any>object[key]);
328
- break;
329
- case "string":
330
- (<string>object[key]) = String(object[key]);
331
- break;
332
- case "boolean":
333
- (<boolean>object[key]) = object[key] === true || object[key] === "true";
334
- break;
335
- default:
336
- rebuildTypes(<UnknownRecord>object[key], <UnknownRecord>types[key]);
337
- break;
338
- }
339
- }
340
- };
341
-
342
- /**
343
- * Fetch process.env[envName] or throw if its undefined
344
- */
345
- export const envOrThrow = (envName: string): string => {
346
- const envValue = process.env[envName];
347
- if (envValue === undefined) throw new Error(`Enviroment variable "${envName}" is undefined!`);
348
- return envValue;
349
- };
package/src/react.ts DELETED
@@ -1,11 +0,0 @@
1
- export const toBase64 = async (file: File): Promise<string | ArrayBuffer> => {
2
- const base64Image = await new Promise<string | ArrayBuffer | null>((resolve, reject) => {
3
- const reader = new FileReader();
4
- reader.readAsDataURL(file);
5
- reader.onload = () => resolve(reader.result);
6
- reader.onerror = reject;
7
- }).catch((err) => err);
8
- if (base64Image instanceof Error) throw new Error(`Failed to convert file ${file.name} to base64.\n${base64Image.message}`);
9
- if (base64Image === undefined || base64Image === null) throw new Error(`Failed to convert file ${file.name} to base64.`);
10
- return base64Image;
11
- };
package/src/test.ts DELETED
@@ -1,86 +0,0 @@
1
- import type { ValueOfA, Primitives, Primitive, UnknownRecord, Constructor } from "./ts.js";
2
-
3
- interface Expect {
4
- any<C>(constructor: C extends Constructor ? C : any): C extends Constructor ? Primitive<C> : C;
5
- arrayContaining<T = unknown>(expected: Array<T>): T[];
6
- objectContaining<T = unknown>(expected: T): T;
7
- stringMatching<T extends string>(expected: T): T;
8
- }
9
- interface ExpectGeneric extends Expect {
10
- (actual: unknown, message?: string): any;
11
- extend(matchers: unknown): void;
12
- }
13
-
14
- export type Matchers = {
15
- typeOrNull: <T extends Primitives>(matcher: T) => Primitive<T> | null;
16
- typeOrUndefined: <T extends Primitives>(matcher: T) => Primitive<T> | undefined;
17
- objectContainingOrEmpty: <T>(matcher: T) => T | UnknownRecord;
18
- objectContainingOrUndefined: <T>(matcher: T) => T | undefined;
19
- objectContainingOrNull: <T>(matcher: T) => T | null;
20
- objectContainingOrEmptyOrNullish: <T>(matcher: T) => T | UnknownRecord | undefined | null;
21
- keylessObjectContaining: <T>(matcher: T) => Record<string, T>;
22
- arrayContainingOrEmpty: <T>(matcher: [T]) => T[] | [];
23
- arrayContainingOrEmptyOrUndefined: <T>(matcher: [T]) => T[] | [] | undefined;
24
- enum: <T extends readonly unknown[]>(matcher: T) => ValueOfA<T>;
25
- };
26
- const OK = {
27
- message: () => "Ok",
28
- pass: true,
29
- };
30
- export type EExpect<T> = Expect & Matchers & T;
31
- export const getExpect = <T extends ExpectGeneric>(expect: T): EExpect<T> => {
32
- const matchers: Record<keyof Matchers, any> = {
33
- typeOrNull(received: unknown, argument: unknown) {
34
- if (received === null) return OK;
35
- expect(received).toStrictEqual(expect.any(argument));
36
- return OK;
37
- },
38
- typeOrUndefined(received: unknown, argument: unknown) {
39
- if (received === undefined) return OK;
40
- expect(received).toStrictEqual(expect.any(argument));
41
- return OK;
42
- },
43
- objectContainingOrEmpty(received: unknown[], argument: unknown) {
44
- if (Object.keys(received).length === 0) return OK;
45
- expect(received).toStrictEqual(expect.objectContaining(argument));
46
- return OK;
47
- },
48
- objectContainingOrUndefined(received: unknown, argument: unknown) {
49
- if (received === undefined) return OK;
50
- expect(received).toStrictEqual(expect.objectContaining(argument));
51
- return OK;
52
- },
53
- objectContainingOrNull(received: unknown, argument: unknown) {
54
- if (received === null) return OK;
55
- expect(received).toStrictEqual(expect.objectContaining(argument));
56
- return OK;
57
- },
58
- objectContainingOrEmptyOrNullish(received: unknown, argument: unknown) {
59
- if (received === undefined || received === null || Object.keys(received).length === 0) return OK;
60
- expect(received).toStrictEqual(expect.objectContaining(argument));
61
- return OK;
62
- },
63
- keylessObjectContaining(received: UnknownRecord, argument: unknown) {
64
- for (const key in received) {
65
- expect(received[key]).toStrictEqual(argument);
66
- }
67
- return OK;
68
- },
69
- arrayContainingOrEmpty(received: unknown[], argument: any[]) {
70
- if (received.length === 0) return OK;
71
- expect(received).toStrictEqual(expect.arrayContaining(argument));
72
- return OK;
73
- },
74
- arrayContainingOrEmptyOrUndefined(received: unknown[], argument: unknown[]) {
75
- if (received === undefined || received.length === 0) return OK;
76
- expect(received).toStrictEqual(expect.arrayContaining(argument));
77
- return OK;
78
- },
79
- enum(received: unknown, argument: unknown[]) {
80
- expect(argument).toContain(received);
81
- return OK;
82
- },
83
- };
84
- expect.extend(matchers);
85
- return <EExpect<T>>expect;
86
- };
package/src/ts/math.ts DELETED
@@ -1,62 +0,0 @@
1
- type Zero<S, Z> = S extends `${infer A}${infer B}` ? (B extends "" ? Z : `${Zero<A, Z>}${Zero<B, Z>}`) : "";
2
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
3
- type ZZero<S, Z> = S extends `${infer _A}${infer B}` ? Zero<B, Z> : "";
4
-
5
- type Increment<T> = T extends "0"
6
- ? "1"
7
- : T extends "1"
8
- ? "2"
9
- : T extends "2"
10
- ? "3"
11
- : T extends "3"
12
- ? "4"
13
- : T extends "4"
14
- ? "5"
15
- : T extends "5"
16
- ? "6"
17
- : T extends "6"
18
- ? "7"
19
- : T extends "7"
20
- ? "8"
21
- : T extends "8"
22
- ? "9"
23
- : never;
24
- export type AddOne<S = string> = S extends "9" ? "10" : _AddOne<S>;
25
- type _AddOne<S = string> = S extends `${infer A}${infer B}`
26
- ? `${Increment<B> extends never ? (_AddOne<B> extends never ? Increment<A> : A) : A}${Increment<B> extends never
27
- ? _AddOne<B> extends never
28
- ? ZZero<S, "0">
29
- : _AddOne<B>
30
- : Increment<B>}`
31
- : never;
32
-
33
- type Decrement<T = string> = T extends "1"
34
- ? "0"
35
- : T extends "2"
36
- ? "1"
37
- : T extends "3"
38
- ? "2"
39
- : T extends "4"
40
- ? "3"
41
- : T extends "5"
42
- ? "4"
43
- : T extends "6"
44
- ? "5"
45
- : T extends "7"
46
- ? "6"
47
- : T extends "8"
48
- ? "7"
49
- : T extends "9"
50
- ? "8"
51
- : never;
52
- export type MinusOne<S = string> = S extends "10" ? "9" : _MinusOne<S>;
53
- type _MinusOne<S = string> = __MinusOne<S> extends `0${infer A}` ? `${A}` : __MinusOne<S>;
54
- type __MinusOne<S = string> = S extends `${infer A}${infer B}`
55
- ? `${Decrement<B> extends never ? (__MinusOne<B> extends never ? Decrement<A> : A) : A}${Decrement<B> extends never
56
- ? __MinusOne<B> extends never
57
- ? ZZero<S, "9">
58
- : __MinusOne<B>
59
- : Decrement<B>}`
60
- : never;
61
-
62
- export type TimesTen<S> = S extends string | number ? `${S}0` : never;
@@ -1,15 +0,0 @@
1
- type BuildPowersOf2LengthArrays<N extends number, R extends never[][]> = R[0][N] extends never ? R : BuildPowersOf2LengthArrays<N, [[...R[0], ...R[0]], ...R]>;
2
- type ConcatLargestUntilDone<N extends number, R extends never[][], B extends never[]> = B["length"] extends N
3
- ? B
4
- : [...R[0], ...B][N] extends never
5
- ? ConcatLargestUntilDone<N, R extends [R[0], ...infer U] ? (U extends never[][] ? U : never) : never, B>
6
- : ConcatLargestUntilDone<N, R extends [R[0], ...infer U] ? (U extends never[][] ? U : never) : never, [...R[0], ...B]>;
7
-
8
- type Replace<R extends any[], T> = { [K in keyof R]: T };
9
- type TupleOf<T, N extends number> = number extends N
10
- ? T[]
11
- : {
12
- [K in N]: BuildPowersOf2LengthArrays<K, [[never]]> extends infer U ? (U extends never[][] ? Replace<ConcatLargestUntilDone<K, U, []>, T> : never) : never;
13
- }[N];
14
- export type RangeOf<N extends number> = Partial<TupleOf<unknown, N>>["length"];
15
- export type NumRangeInclusive<FROM extends number, TO extends number> = Exclude<RangeOf<TO>, RangeOf<FROM>> | FROM;
package/src/ts.ts DELETED
@@ -1,54 +0,0 @@
1
- export type { RangeOf, NumRangeInclusive } from "./ts/numRange.js";
2
- export type { AddOne, MinusOne, TimesTen } from "./ts/math.js";
3
-
4
- export type ValueOf<T> = T[keyof T];
5
- export type ValueOfA<T extends unknown[] | readonly unknown[]> = T[number];
6
-
7
- export type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never;
8
-
9
- export type RecursivePartial<T> = {
10
- [P in keyof T]?: T[P] extends (infer U)[] ? RecursivePartial<U>[] : T[P] extends object ? RecursivePartial<T[P]> : T[P];
11
- };
12
-
13
- export type ToStrUnion<T extends string | number | bigint | boolean | null | undefined> = `${T}`;
14
-
15
- export type FirstChar<T> = T extends `${infer C}${string}` ? C : never;
16
- export type LastChar<T> = T extends `${string}${infer C}` ? C : never;
17
-
18
- /**
19
- * Takes in a string padded with 0's and returns the unpadded string;
20
- */
21
- export type UnPad<N extends string> = N extends "0" ? "0" : N extends `0${infer A}` ? UnPad<A> : N;
22
-
23
- /**
24
- * Returns a type guard to validate a passed key is a keyof given record
25
- */
26
- export const generateIsKeyof =
27
- <T extends Record<string | number | symbol, unknown>>(record: T) =>
28
- (key: any): key is keyof T =>
29
- key in record;
30
-
31
- export const isDefined = <T>(O: T | undefined): O is T => O !== undefined;
32
-
33
- export type RequiredKeys<T> = keyof T extends infer K extends PropertyKey ? (K extends K ? (T extends Record<K, unknown> ? K : never) : never) : never;
34
- export type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
35
- export type RequiredOnly<T> = Pick<T, RequiredKeys<T> & keyof T>;
36
- export type OptionalOnly<T> = Pick<T, OptionalKeys<T> & keyof T>;
37
-
38
- export type UnknownRecord = Record<string | number | symbol, unknown>;
39
-
40
- export type Constructor = abstract new (...args: any) => any;
41
- export type Primitives = StringConstructor | NumberConstructor | BooleanConstructor;
42
- export type Primitive<T> = T extends string
43
- ? string
44
- : T extends StringConstructor
45
- ? string
46
- : T extends number
47
- ? number
48
- : T extends NumberConstructor
49
- ? number
50
- : T extends boolean
51
- ? boolean
52
- : T extends BooleanConstructor
53
- ? boolean
54
- : T;