@inrixia/helpers 2.0.1 → 2.0.3

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 (65) hide show
  1. package/README.md +1 -0
  2. package/package.json +44 -8
  3. package/{conv.js → src/conv.ts} +15 -13
  4. package/src/elastic.ts +141 -0
  5. package/src/geo.ts +33 -0
  6. package/{index.js → src/index.ts} +9 -10
  7. package/src/logic.ts +52 -0
  8. package/{math.js → src/math.ts} +20 -19
  9. package/src/object.ts +349 -0
  10. package/src/react.ts +11 -0
  11. package/src/test/matchers.ts +76 -0
  12. package/src/test.ts +14 -0
  13. package/src/ts/math.ts +62 -0
  14. package/src/ts/numRange.ts +15 -0
  15. package/src/ts.ts +54 -0
  16. package/tsconfig.json +22 -0
  17. package/conv.d.ts +0 -28
  18. package/conv.d.ts.map +0 -1
  19. package/conv.js.map +0 -1
  20. package/elastic.d.ts +0 -54
  21. package/elastic.d.ts.map +0 -1
  22. package/elastic.js +0 -150
  23. package/elastic.js.map +0 -1
  24. package/geo.d.ts +0 -19
  25. package/geo.d.ts.map +0 -1
  26. package/geo.js +0 -32
  27. package/geo.js.map +0 -1
  28. package/index.d.ts +0 -10
  29. package/index.d.ts.map +0 -1
  30. package/index.js.map +0 -1
  31. package/logic.d.ts +0 -23
  32. package/logic.d.ts.map +0 -1
  33. package/logic.js +0 -50
  34. package/logic.js.map +0 -1
  35. package/math.d.ts +0 -35
  36. package/math.d.ts.map +0 -1
  37. package/math.js.map +0 -1
  38. package/object.d.ts +0 -169
  39. package/object.d.ts.map +0 -1
  40. package/object.js +0 -349
  41. package/object.js.map +0 -1
  42. package/react.d.ts +0 -2
  43. package/react.d.ts.map +0 -1
  44. package/react.js +0 -14
  45. package/react.js.map +0 -1
  46. package/test/matchers.d.ts +0 -15
  47. package/test/matchers.d.ts.map +0 -1
  48. package/test/matchers.js +0 -66
  49. package/test/matchers.js.map +0 -1
  50. package/test.d.ts +0 -15
  51. package/test.d.ts.map +0 -1
  52. package/test.js +0 -5
  53. package/test.js.map +0 -1
  54. package/ts/math.d.ts +0 -12
  55. package/ts/math.d.ts.map +0 -1
  56. package/ts/math.js +0 -2
  57. package/ts/math.js.map +0 -1
  58. package/ts/numRange.d.ts +0 -12
  59. package/ts/numRange.d.ts.map +0 -1
  60. package/ts/numRange.js +0 -2
  61. package/ts/numRange.js.map +0 -1
  62. package/ts.d.ts +0 -29
  63. package/ts.d.ts.map +0 -1
  64. package/ts.js +0 -6
  65. 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,54 @@
1
1
  {
2
2
  "name": "@inrixia/helpers",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "description": "Helper functions for various projects",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "type": "module",
8
8
  "scripts": {
9
- "tsc": "rmdir dist /s /Q && mkdir dist && copy /Y package.json dist && tsc",
10
- "send": "npm run tsc && cd ./dist && npm publish"
9
+ "postinstall": "tsc"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ },
16
+ "./conv": {
17
+ "types": "./dist/conv.d.ts",
18
+ "import": "./dist/conv.js"
19
+ },
20
+ "./elastic": {
21
+ "types": "./dist/elastic.d.ts",
22
+ "import": "./dist/elastic.js"
23
+ },
24
+ "./geo": {
25
+ "types": "./dist/geo.d.ts",
26
+ "import": "./dist/geo.js"
27
+ },
28
+ "./logic": {
29
+ "types": "./dist/logic.d.ts",
30
+ "import": "./dist/logic.js"
31
+ },
32
+ "./math": {
33
+ "types": "./dist/math.d.ts",
34
+ "import": "./dist/math.js"
35
+ },
36
+ "./object": {
37
+ "types": "./dist/object.d.ts",
38
+ "import": "./dist/object.js"
39
+ },
40
+ "./react": {
41
+ "types": "./dist/react.d.ts",
42
+ "import": "./dist/react.js"
43
+ },
44
+ "./test": {
45
+ "types": "./dist/test.d.ts",
46
+ "import": "./dist/test.js"
47
+ },
48
+ "./ts": {
49
+ "types": "./dist/ts.d.ts",
50
+ "import": "./dist/ts.js"
51
+ }
11
52
  },
12
53
  "repository": {
13
54
  "type": "git",
@@ -23,12 +64,7 @@
23
64
  "@types/elasticsearch": "^5.0.40",
24
65
  "@types/node": "^18.7.18",
25
66
  "@typescript-eslint/eslint-plugin": "^5.37.0",
26
- "@typescript-eslint/parser": "^5.37.0",
27
67
  "eslint": "^8.23.1",
28
- "eslint-config-standard-with-typescript": "^23.0.0",
29
- "eslint-plugin-import": "^2.26.0",
30
- "eslint-plugin-n": "^15.2.5",
31
- "eslint-plugin-promise": "^6.0.1",
32
68
  "typescript": "^4.8.3",
33
69
  "vitest": "^0.23.4"
34
70
  }
@@ -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
- const lnRH = Math.log(relativeHumidity / 100);
13
- const aTdbTd = (a * dewPointTemp) / (b + dewPointTemp);
14
- return (b * (aTdbTd - lnRH)) / (a + lnRH - aTdbTd);
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
- const lnRH = Math.log(relativeHumidity / 100);
26
- const aTbT = (a * dryBulbTemp) / (b + dryBulbTemp);
27
- return (b * (lnRH + aTbT)) / (a - lnRH - aTbT);
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
- const aTdbTd = (a * dewPointTemp) / (b + dewPointTemp);
39
- const aTbT = (a * dryBulbTemp) / (b + dryBulbTemp);
40
- return 100 * (Math.exp(aTdbTd) / Math.exp(aTbT));
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/elastic.ts ADDED
@@ -0,0 +1,141 @@
1
+ import type { Client, SearchParams, SearchResponse, IndicesCreateParams } from "elasticsearch";
2
+ import type { UnknownRecord } from "./ts.js";
3
+
4
+ import { EventEmitter } from "events";
5
+
6
+ /**
7
+ * Indexes a large amount of entities in a single query
8
+ * @param entities Array containing entities to index
9
+ * @param indexName Name of index to index entities.
10
+ *
11
+ * @returns Promise that resolves time taken to index entities in ms.
12
+ */
13
+ export const bulkIndex = async (elastic: Client, entities: UnknownRecord[], indexName: string, refresh = false): Promise<number> =>
14
+ elastic.bulk({
15
+ refresh: refresh,
16
+ body: entities.flatMap((entity) => [{ index: { _index: indexName } }, entity]),
17
+ });
18
+
19
+ /**
20
+ * Queries elastic using `params`.
21
+ * @param params Query object.
22
+ *
23
+ * @returns Iterator that yeilds a result until query exhausted.
24
+ */
25
+ export async function* scrollSearch(elastic: Client, params: SearchParams): AsyncGenerator<SearchResponse<unknown>> {
26
+ if (params.scroll === undefined) throw new Error("params.scroll is required!");
27
+ let response = await elastic.search(params);
28
+ let nextResponse;
29
+ while (true) {
30
+ nextResponse = elastic.scroll({
31
+ scrollId: response._scroll_id!,
32
+ scroll: params.scroll,
33
+ });
34
+ if (!response._scroll_id) break;
35
+ if (response.hits.hits.length === 0) break;
36
+ yield response;
37
+ response = await nextResponse;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Function to recreate a elasticsearch index.
43
+ * @param elastic Elasticsearch client
44
+ * @param createParams Elastic parameters for creation of index
45
+ * @param options Options for creation
46
+ */
47
+ export const createIndex = async (
48
+ elastic: Client,
49
+ createParams: IndicesCreateParams,
50
+ options: { logProgress?: boolean; destoryIfExists: boolean }
51
+ ): Promise<void> => {
52
+ if (!options) throw new Error("Options required!");
53
+ if (!createParams) throw new Error("Elastic parameters required! (createParams)");
54
+ if (!options.logProgress) options.logProgress = false;
55
+ if (options.destoryIfExists) {
56
+ try {
57
+ await elastic.indices.exists({ index: createParams.index });
58
+ } catch (err) {
59
+ if (err instanceof Error) err.message = "Failed to check if old index exists!\n" + err.message;
60
+ throw err;
61
+ }
62
+ if (options.logProgress) process.stdout.write(`Deleting index "${createParams.index}"...`);
63
+ try {
64
+ await elastic.indices.delete({ index: createParams.index });
65
+ } catch (err) {
66
+ if (err instanceof Error) err.message = "Failed to delete old index!\n" + err.message;
67
+ throw err;
68
+ }
69
+ if (options.logProgress) process.stdout.write(` Deleted!\nCreating index "${createParams.index}"...`);
70
+ try {
71
+ await elastic.indices.create(createParams);
72
+ } catch (err) {
73
+ if (err instanceof Error) err.message = "Failed to create new index!\n" + err.message;
74
+ throw err;
75
+ }
76
+ if (options.logProgress) process.stdout.write(" Created!\n");
77
+ } else {
78
+ if (options.logProgress) process.stdout.write(`Creating index "${createParams.index}"...`);
79
+ try {
80
+ await elastic.indices.create(createParams);
81
+ } catch (err) {
82
+ if (err instanceof Error) err.message = "Failed to create new index!\n" + err.message;
83
+ throw err;
84
+ }
85
+ if (options.logProgress) process.stdout.write(" Created!\n");
86
+ }
87
+ };
88
+
89
+ /**
90
+ * Returns scrollsearch results in simulated time based on when result timestamp.
91
+ * @param elastic Elasticsearch client to use
92
+ * @param query Query object to use for scroll search
93
+ * @param timestampKey Key to use for fetching timestamp from objects
94
+ * @param options.timescale Rate at which "time" progreesses
95
+ * @returns EventEmitter which emits 'entity' events containing resulting hits
96
+ * @example
97
+ * const elasticClient = new ElasticClient({ node: 'http://127.0.0.1:9200' })
98
+ * const timestamp = "reportedTime"
99
+ * const query = {
100
+ * index: "documents_index",
101
+ * scroll: '10m',
102
+ * body: {
103
+ * "query": { "match_all": {} },
104
+ * "sort": [{ [timestamp]: {"order": "asc"} }],
105
+ * "size": 10000
106
+ * }
107
+ * }
108
+ * stream(elasticClient, query, timestamp, 2).on('entity', console.log) // <- Emitted results based on time moving at 2x normal speed
109
+ */
110
+ export const stream = (
111
+ elastic: Client,
112
+ query: SearchParams,
113
+ timestampKey: string,
114
+ options: { timescale: number; logProgress: boolean } = { timescale: 1, logProgress: false }
115
+ ): EventEmitter => {
116
+ const entityReceiver = new EventEmitter();
117
+ (async () => {
118
+ if (options.timescale === undefined) options.timescale = 1;
119
+ if (typeof options.timescale !== "number") throw new Error("options.timescale must be a number!");
120
+ if (timestampKey === undefined) throw new Error("timestampKey is undefined!");
121
+ let timeOffset: number | undefined;
122
+ let startDate = Date.now();
123
+
124
+ if (options.logProgress) console.log("Beginning elastic scroll for entity streaming...");
125
+ for await (const result of scrollSearch(elastic, query) as AsyncGenerator<SearchResponse<{ [timestampKey: string]: number }>>) {
126
+ if (options.logProgress) console.log(`Query iteration finished, streaming ${result.hits.hits.length} entities.`);
127
+ if (timeOffset === undefined) {
128
+ timeOffset = Date.now() - new Date(result.hits.hits[0]._source[timestampKey]).getTime();
129
+ startDate = Date.now();
130
+ }
131
+ for (const entity of result.hits.hits) {
132
+ const offsetEntityTime = new Date(entity._source[timestampKey]).getTime() + timeOffset;
133
+ while (Date.now() + (Date.now() - startDate) * options.timescale < offsetEntityTime) {
134
+ // Spin while waiting to emit next entity
135
+ }
136
+ entityReceiver.emit("entity", entity._source);
137
+ }
138
+ }
139
+ })();
140
+ return entityReceiver;
141
+ };
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,9 @@
1
- export * from "./conv.js";
2
- export * from "./elastic.js";
3
- export * from "./geo.js";
4
- export * from "./logic.js";
5
- export * from "./math.js";
6
- export * from "./object.js";
7
- export * from "./react.js";
8
- export * from "./test.js";
9
- export * from "./ts.js";
10
- //# sourceMappingURL=index.js.map
1
+ export * from "./conv.js";
2
+ export * from "./elastic.js";
3
+ export * from "./geo.js";
4
+ export * from "./logic.js";
5
+ export * from "./math.js";
6
+ export * from "./object.js";
7
+ export * from "./react.js";
8
+ export * from "./test.js";
9
+ 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
+ };
@@ -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
- let difference = Math.abs(angle1 - angle2) % 360;
10
- difference = difference > 180 ? 360 - difference : difference;
11
- // Calculate sign
12
- if (signed)
13
- return (angle1 - angle2 >= 0 && angle1 - angle2 <= 180) || (angle1 - angle2 <= -180 && angle1 - angle2 >= -360) ? difference : difference * -1;
14
- return difference;
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
- angle = angle % 360;
23
- return angle < 0 ? angle + 360 : angle;
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
- digits = 10 ** digits;
33
- return ~~(num * digits) / digits;
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
- num = num.toString();
49
- while (num.length < zeros)
50
- num = "0" + num;
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