@inrixia/helpers 2.0.2 → 2.0.4
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 +1 -0
- package/package.json +42 -13
- package/{conv.js → src/conv.ts} +15 -13
- package/src/geo.ts +33 -0
- package/{index.js → src/index.ts} +8 -10
- package/src/logic.ts +52 -0
- package/{math.js → src/math.ts} +20 -19
- package/src/object.ts +349 -0
- package/src/react.ts +11 -0
- package/src/test.ts +86 -0
- package/src/ts/math.ts +62 -0
- package/src/ts/numRange.ts +15 -0
- package/src/ts.ts +54 -0
- package/tsconfig.json +22 -0
- package/conv.d.ts +0 -28
- package/conv.d.ts.map +0 -1
- package/conv.js.map +0 -1
- package/elastic.d.ts +0 -54
- package/elastic.d.ts.map +0 -1
- package/elastic.js +0 -150
- package/elastic.js.map +0 -1
- package/geo.d.ts +0 -19
- package/geo.d.ts.map +0 -1
- package/geo.js +0 -32
- package/geo.js.map +0 -1
- package/index.d.ts +0 -10
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/logic.d.ts +0 -23
- package/logic.d.ts.map +0 -1
- package/logic.js +0 -50
- package/logic.js.map +0 -1
- package/math.d.ts +0 -35
- package/math.d.ts.map +0 -1
- package/math.js.map +0 -1
- package/object.d.ts +0 -169
- package/object.d.ts.map +0 -1
- package/object.js +0 -349
- package/object.js.map +0 -1
- package/react.d.ts +0 -2
- package/react.d.ts.map +0 -1
- package/react.js +0 -14
- package/react.js.map +0 -1
- package/test/matchers.d.ts +0 -15
- package/test/matchers.d.ts.map +0 -1
- package/test/matchers.js +0 -69
- package/test/matchers.js.map +0 -1
- package/test.d.ts +0 -14
- package/test.d.ts.map +0 -1
- package/test.js +0 -2
- package/test.js.map +0 -1
- package/ts/math.d.ts +0 -12
- package/ts/math.d.ts.map +0 -1
- package/ts/math.js +0 -2
- package/ts/math.js.map +0 -1
- package/ts/numRange.d.ts +0 -12
- package/ts/numRange.d.ts.map +0 -1
- package/ts/numRange.js +0 -2
- package/ts/numRange.js.map +0 -1
- package/ts.d.ts +0 -29
- package/ts.d.ts.map +0 -1
- package/ts.js +0 -6
- package/ts.js.map +0 -1
package/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Helpers for various projects
|
package/package.json
CHANGED
|
@@ -1,13 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inrixia/helpers",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.4",
|
|
4
4
|
"description": "Helper functions for various projects",
|
|
5
|
-
"main": "index.js",
|
|
6
|
-
"types": "index.d.ts",
|
|
7
5
|
"type": "module",
|
|
8
6
|
"scripts": {
|
|
9
|
-
"
|
|
10
|
-
"
|
|
7
|
+
"postinstall": "tsc",
|
|
8
|
+
"prepublish": "tsc"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./conv": {
|
|
16
|
+
"types": "./dist/conv.d.ts",
|
|
17
|
+
"import": "./dist/conv.js"
|
|
18
|
+
},
|
|
19
|
+
"./geo": {
|
|
20
|
+
"types": "./dist/geo.d.ts",
|
|
21
|
+
"import": "./dist/geo.js"
|
|
22
|
+
},
|
|
23
|
+
"./logic": {
|
|
24
|
+
"types": "./dist/logic.d.ts",
|
|
25
|
+
"import": "./dist/logic.js"
|
|
26
|
+
},
|
|
27
|
+
"./math": {
|
|
28
|
+
"types": "./dist/math.d.ts",
|
|
29
|
+
"import": "./dist/math.js"
|
|
30
|
+
},
|
|
31
|
+
"./object": {
|
|
32
|
+
"types": "./dist/object.d.ts",
|
|
33
|
+
"import": "./dist/object.js"
|
|
34
|
+
},
|
|
35
|
+
"./react": {
|
|
36
|
+
"types": "./dist/react.d.ts",
|
|
37
|
+
"import": "./dist/react.js"
|
|
38
|
+
},
|
|
39
|
+
"./test": {
|
|
40
|
+
"types": "./dist/test.d.ts",
|
|
41
|
+
"import": "./dist/test.js"
|
|
42
|
+
},
|
|
43
|
+
"./ts": {
|
|
44
|
+
"types": "./dist/ts.d.ts",
|
|
45
|
+
"import": "./dist/ts.js"
|
|
46
|
+
}
|
|
11
47
|
},
|
|
12
48
|
"repository": {
|
|
13
49
|
"type": "git",
|
|
@@ -20,16 +56,9 @@
|
|
|
20
56
|
},
|
|
21
57
|
"homepage": "https://github.com/Inrixia/Helpers#readme",
|
|
22
58
|
"devDependencies": {
|
|
23
|
-
"@types/elasticsearch": "^5.0.40",
|
|
24
59
|
"@types/node": "^18.7.18",
|
|
25
60
|
"@typescript-eslint/eslint-plugin": "^5.37.0",
|
|
26
|
-
"@typescript-eslint/parser": "^5.37.0",
|
|
27
61
|
"eslint": "^8.23.1",
|
|
28
|
-
"
|
|
29
|
-
"eslint-plugin-import": "^2.26.0",
|
|
30
|
-
"eslint-plugin-n": "^15.2.5",
|
|
31
|
-
"eslint-plugin-promise": "^6.0.1",
|
|
32
|
-
"typescript": "^4.8.3",
|
|
33
|
-
"vitest": "^0.23.4"
|
|
62
|
+
"typescript": "^4.8.3"
|
|
34
63
|
}
|
|
35
64
|
}
|
package/{conv.js → src/conv.ts}
RENAMED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const a = 17.625;
|
|
2
2
|
const b = 243.04;
|
|
3
|
+
|
|
3
4
|
/**
|
|
4
5
|
* Get `dryBulbTemp` from `dewBulbTemp` and `relativeHumidity`
|
|
5
6
|
* @param dewPointTemp Dew point temperature in degrees celsius
|
|
@@ -8,11 +9,12 @@ const b = 243.04;
|
|
|
8
9
|
*
|
|
9
10
|
* @url https://bmcnoldy.rsmas.miami.edu/humidity_conversions.pdf
|
|
10
11
|
*/
|
|
11
|
-
export const dryBulbTemp = (dewPointTemp, relativeHumidity) => {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
export const dryBulbTemp = (dewPointTemp: number, relativeHumidity: number): number => {
|
|
13
|
+
const lnRH = Math.log(relativeHumidity / 100);
|
|
14
|
+
const aTdbTd = (a * dewPointTemp) / (b + dewPointTemp);
|
|
15
|
+
return (b * (aTdbTd - lnRH)) / (a + lnRH - aTdbTd);
|
|
15
16
|
};
|
|
17
|
+
|
|
16
18
|
/**
|
|
17
19
|
* Get `dewPointTemp` from `dryBulbTemp` and `relativeHumidity`
|
|
18
20
|
* @param dryBulbTemp Dry bulb temperature in degrees celsius
|
|
@@ -21,11 +23,12 @@ export const dryBulbTemp = (dewPointTemp, relativeHumidity) => {
|
|
|
21
23
|
*
|
|
22
24
|
* @url https://bmcnoldy.rsmas.miami.edu/humidity_conversions.pdf
|
|
23
25
|
*/
|
|
24
|
-
export const dewPointTemp = (dryBulbTemp, relativeHumidity) => {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
export const dewPointTemp = (dryBulbTemp: number, relativeHumidity: number): number => {
|
|
27
|
+
const lnRH = Math.log(relativeHumidity / 100);
|
|
28
|
+
const aTbT = (a * dryBulbTemp) / (b + dryBulbTemp);
|
|
29
|
+
return (b * (lnRH + aTbT)) / (a - lnRH - aTbT);
|
|
28
30
|
};
|
|
31
|
+
|
|
29
32
|
/**
|
|
30
33
|
* Get `relativeHumidity` from `dryBulbTemp` and `dewPointTemp`
|
|
31
34
|
* @param dryBulbTemp Dry bulb temperature in degrees celsius
|
|
@@ -34,9 +37,8 @@ export const dewPointTemp = (dryBulbTemp, relativeHumidity) => {
|
|
|
34
37
|
*
|
|
35
38
|
* @url https://bmcnoldy.rsmas.miami.edu/humidity_conversions.pdf
|
|
36
39
|
*/
|
|
37
|
-
export const relativeHumidity = (dryBulbTemp, dewPointTemp) => {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
export const relativeHumidity = (dryBulbTemp: number, dewPointTemp: number): number => {
|
|
41
|
+
const aTdbTd = (a * dewPointTemp) / (b + dewPointTemp);
|
|
42
|
+
const aTbT = (a * dryBulbTemp) / (b + dryBulbTemp);
|
|
43
|
+
return 100 * (Math.exp(aTdbTd) / Math.exp(aTbT));
|
|
41
44
|
};
|
|
42
|
-
//# sourceMappingURL=conv.js.map
|
package/src/geo.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
};
|
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
export * from "./conv.js";
|
|
2
|
-
export * from "./
|
|
3
|
-
export * from "./
|
|
4
|
-
export * from "./
|
|
5
|
-
export * from "./
|
|
6
|
-
export * from "./
|
|
7
|
-
export * from "./
|
|
8
|
-
export * from "./
|
|
9
|
-
export * from "./ts.js";
|
|
10
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
export * from "./conv.js";
|
|
2
|
+
export * from "./geo.js";
|
|
3
|
+
export * from "./logic.js";
|
|
4
|
+
export * from "./math.js";
|
|
5
|
+
export * from "./object.js";
|
|
6
|
+
export * from "./react.js";
|
|
7
|
+
export * from "./test.js";
|
|
8
|
+
export * from "./ts.js";
|
package/src/logic.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
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/{math.js → src/math.ts}
RENAMED
|
@@ -5,33 +5,36 @@
|
|
|
5
5
|
* @param signed If the result is signed or absolute
|
|
6
6
|
* @returns The difference in degrees
|
|
7
7
|
*/
|
|
8
|
-
export const angleDifference = (angle1, angle2, signed = true) => {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
export const angleDifference = (angle1: number, angle2: number, signed = true): number => {
|
|
9
|
+
let difference = Math.abs(angle1 - angle2) % 360;
|
|
10
|
+
difference = difference > 180 ? 360 - difference : difference;
|
|
11
|
+
|
|
12
|
+
// Calculate sign
|
|
13
|
+
if (signed) return (angle1 - angle2 >= 0 && angle1 - angle2 <= 180) || (angle1 - angle2 <= -180 && angle1 - angle2 >= -360) ? difference : difference * -1;
|
|
14
|
+
return difference;
|
|
15
15
|
};
|
|
16
|
+
|
|
16
17
|
/**
|
|
17
18
|
* Converts `angle` to 0°-360°
|
|
18
19
|
* @param angle
|
|
19
20
|
* @returns `angle` in 0-360°
|
|
20
21
|
*/
|
|
21
|
-
export const to360 = (angle) => {
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
export const to360 = (angle: number): number => {
|
|
23
|
+
angle = angle % 360;
|
|
24
|
+
return angle < 0 ? angle + 360 : angle;
|
|
24
25
|
};
|
|
26
|
+
|
|
25
27
|
/**
|
|
26
28
|
* Rounds a number to `digits` decimal places.
|
|
27
29
|
* @param num Number to round
|
|
28
30
|
* @param digits Decimal places to round to
|
|
29
31
|
* @returns Rounded number
|
|
30
32
|
*/
|
|
31
|
-
export const qRnd = (num, digits = 0) => {
|
|
32
|
-
|
|
33
|
-
|
|
33
|
+
export const qRnd = (num: number, digits = 0): number => {
|
|
34
|
+
digits = 10 ** digits;
|
|
35
|
+
return ~~(num * digits) / digits;
|
|
34
36
|
};
|
|
37
|
+
|
|
35
38
|
/**
|
|
36
39
|
* Pad a number with 0's
|
|
37
40
|
* @param num Number to pad.
|
|
@@ -44,10 +47,8 @@ export const qRnd = (num, digits = 0) => {
|
|
|
44
47
|
* let triplePaddedNumber = nPad(6, 3)
|
|
45
48
|
* // triplePaddedNumber = "006"
|
|
46
49
|
*/
|
|
47
|
-
export const nPad = (num, zeros = 2) => {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
return num;
|
|
50
|
+
export const nPad = (num: number | string, zeros = 2): string => {
|
|
51
|
+
num = num.toString();
|
|
52
|
+
while (num.length < zeros) num = "0" + num;
|
|
53
|
+
return num;
|
|
52
54
|
};
|
|
53
|
-
//# sourceMappingURL=math.js.map
|
package/src/object.ts
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
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
|
+
};
|