@webdeveric/utils 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/cjs/asArray.js.map +1 -1
  2. package/dist/cjs/convert.js.map +1 -1
  3. package/dist/cjs/delay.js.map +1 -1
  4. package/dist/cjs/delayAnimationFrame.js.map +1 -1
  5. package/dist/cjs/getMaxValue.js.map +1 -1
  6. package/dist/cjs/getMinValue.js.map +1 -1
  7. package/dist/cjs/getOwnProperties.js +1 -4
  8. package/dist/cjs/getOwnProperties.js.map +1 -1
  9. package/dist/cjs/isEmpty.js +5 -1
  10. package/dist/cjs/isEmpty.js.map +1 -1
  11. package/dist/cjs/node/fcrdns.js.map +1 -1
  12. package/dist/cjs/normalize.js +0 -15
  13. package/dist/cjs/normalize.js.map +1 -1
  14. package/dist/cjs/secToString.js.map +1 -1
  15. package/dist/cjs/toPascalCase.js +1 -4
  16. package/dist/cjs/toPascalCase.js.map +1 -1
  17. package/dist/cjs/type-assertion.js.map +1 -1
  18. package/dist/cjs/type-predicate.js +5 -1
  19. package/dist/cjs/type-predicate.js.map +1 -1
  20. package/dist/cjs/uniqueItems.js.map +1 -1
  21. package/dist/cjs/until.js.map +1 -1
  22. package/dist/mjs/asArray.js.map +1 -1
  23. package/dist/mjs/convert.js.map +1 -1
  24. package/dist/mjs/delay.js.map +1 -1
  25. package/dist/mjs/delayAnimationFrame.js.map +1 -1
  26. package/dist/mjs/getMaxValue.js.map +1 -1
  27. package/dist/mjs/getMinValue.js.map +1 -1
  28. package/dist/mjs/getOwnProperties.js +1 -4
  29. package/dist/mjs/getOwnProperties.js.map +1 -1
  30. package/dist/mjs/isEmpty.js +5 -1
  31. package/dist/mjs/isEmpty.js.map +1 -1
  32. package/dist/mjs/node/fcrdns.js.map +1 -1
  33. package/dist/mjs/normalize.js +0 -15
  34. package/dist/mjs/normalize.js.map +1 -1
  35. package/dist/mjs/secToString.js.map +1 -1
  36. package/dist/mjs/toPascalCase.js +1 -4
  37. package/dist/mjs/toPascalCase.js.map +1 -1
  38. package/dist/mjs/type-assertion.js.map +1 -1
  39. package/dist/mjs/type-predicate.js +3 -0
  40. package/dist/mjs/type-predicate.js.map +1 -1
  41. package/dist/mjs/uniqueItems.js.map +1 -1
  42. package/dist/mjs/until.js.map +1 -1
  43. package/dist/types/asArray.d.ts.map +1 -1
  44. package/dist/types/delay.d.ts.map +1 -1
  45. package/dist/types/delayAnimationFrame.d.ts.map +1 -1
  46. package/dist/types/getMaxValue.d.ts.map +1 -1
  47. package/dist/types/getMinValue.d.ts.map +1 -1
  48. package/dist/types/getOwnProperties.d.ts.map +1 -1
  49. package/dist/types/isEmpty.d.ts.map +1 -1
  50. package/dist/types/node/fcrdns.d.ts.map +1 -1
  51. package/dist/types/normalize.d.ts +4 -2
  52. package/dist/types/normalize.d.ts.map +1 -1
  53. package/dist/types/secToString.d.ts.map +1 -1
  54. package/dist/types/toPascalCase.d.ts.map +1 -1
  55. package/dist/types/type-predicate.d.ts +3 -0
  56. package/dist/types/type-predicate.d.ts.map +1 -1
  57. package/dist/types/types.d.ts +3 -0
  58. package/dist/types/types.d.ts.map +1 -1
  59. package/dist/types/uniqueItems.d.ts.map +1 -1
  60. package/dist/types/until.d.ts.map +1 -1
  61. package/package.json +19 -3
  62. package/src/asArray.ts +2 -3
  63. package/src/convert.ts +1 -1
  64. package/src/delay.ts +6 -7
  65. package/src/delayAnimationFrame.ts +6 -8
  66. package/src/getMaxValue.ts +4 -6
  67. package/src/getMinValue.ts +4 -6
  68. package/src/getOwnProperties.ts +1 -4
  69. package/src/isEmpty.ts +8 -2
  70. package/src/node/fcrdns.ts +10 -16
  71. package/src/normalize.ts +26 -9
  72. package/src/secToString.ts +19 -22
  73. package/src/toPascalCase.ts +9 -13
  74. package/src/type-assertion.ts +3 -3
  75. package/src/type-predicate.ts +5 -1
  76. package/src/types.ts +7 -0
  77. package/src/uniqueItems.ts +2 -3
  78. package/src/until.ts +29 -32
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AACA,oBAAY,SAAS,GAAG,MAAM,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;AAEjD,oBAAY,aAAa,GAAG,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAEzD,oBAAY,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,IAAI,GAAG,CAAC,EAAE,SAAS,GAAG,MAAM,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,KAAK,CAAC;AAE5G,oBAAY,YAAY,GAAG,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC;AAE3D,oBAAY,WAAW,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC;AAExD,oBAAY,UAAU,CAAC,CAAC,IAAI,MAAM,CAAC,GAAG,MAAM,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AACA,oBAAY,SAAS,GAAG,MAAM,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;AAEjD,oBAAY,aAAa,GAAG,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAEzD,oBAAY,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,IAAI,GAAG,CAAC,EAAE,SAAS,GAAG,MAAM,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,KAAK,CAAC;AAE5G,oBAAY,YAAY,GAAG,MAAM,GAAG,MAAM,GAAG,aAAa,CAAC;AAE3D,oBAAY,WAAW,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC;AAExD,oBAAY,UAAU,CAAC,CAAC,IAAI,MAAM,CAAC,GAAG,MAAM,CAAC;AAE7C,oBAAY,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,SAAS,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAE7D,oBAAY,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAG3D,oBAAY,iBAAiB,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"uniqueItems.d.ts","sourceRoot":"","sources":["../../src/uniqueItems.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW,CAAC,CAAC,EAAG,IAAI,EAAE,CAAC,EAAE,GAAK,CAAC,EAAE,CAGhD"}
1
+ {"version":3,"file":"uniqueItems.d.ts","sourceRoot":"","sources":["../../src/uniqueItems.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAE7C"}
@@ -1 +1 @@
1
- {"version":3,"file":"until.d.ts","sourceRoot":"","sources":["../../src/until.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAGzC,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,YAAY,CAAC;CACvB;AAED,oBAAY,OAAO,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,YAAY,CAAC,KAAK,MAAM,CAAC;AAElE,oBAAY,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;AAErC,oBAAY,YAAY,GAAG;IACzB,KAAK,EAAE,KAAK,CAAC;IACb,OAAO,CAAC,EAAE,KAAK,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,oBAAY,aAAa,CAAC,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AAElD,oBAAY,SAAS,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;AAE7D,oBAAY,QAAQ,GAAG,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC;AAE/C,oBAAY,aAAa,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAMlH;;GAEG;AACH,wBAAgB,KAAK,CAAC,CAAC,EAAG,EAAE,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,OAAO,GAAE,YAA6B,GAAK,OAAO,CAAC,CAAC,CAAC,CAiGpG"}
1
+ {"version":3,"file":"until.d.ts","sourceRoot":"","sources":["../../src/until.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAGzC,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,YAAY,CAAC;CACvB;AAED,oBAAY,OAAO,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,YAAY,CAAC,KAAK,MAAM,CAAC;AAElE,oBAAY,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;AAErC,oBAAY,YAAY,GAAG;IACzB,KAAK,EAAE,KAAK,CAAC;IACb,OAAO,CAAC,EAAE,KAAK,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,oBAAY,aAAa,CAAC,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AAElD,oBAAY,SAAS,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;AAE7D,oBAAY,QAAQ,GAAG,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC;AAE/C,oBAAY,aAAa,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAMlH;;GAEG;AACH,wBAAgB,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,OAAO,GAAE,YAA6B,GAAG,OAAO,CAAC,CAAC,CAAC,CA8FjG"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@webdeveric/utils",
3
3
  "description": "Just another collection of utilities.",
4
- "version": "0.13.0",
4
+ "version": "0.14.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -29,7 +29,7 @@
29
29
  "trimEnd",
30
30
  "trimStart",
31
31
  "type-assertion",
32
- "types",
32
+ "type-predicate",
33
33
  "uniqueItems",
34
34
  "until"
35
35
  ],
@@ -82,7 +82,17 @@
82
82
  "validate": "./bin/validate.cjs",
83
83
  "update-keywords": "./bin/update-keywords.mjs",
84
84
  "spellcheck": "cspell './{.github,src,test}/**/*.{ts,json}' './*.{md,js}' './package.json' --no-progress",
85
- "prepublishOnly": "npm run typecheck && npm run spellcheck && npm run lint && npm test && npm run build"
85
+ "prepublishOnly": "npm run typecheck && npm run spellcheck && npm run lint && npm test && npm run build",
86
+ "format": "prettier --write ./*.{js,json,md} ./src/ ./test/",
87
+ "prepare": "husky install"
88
+ },
89
+ "prettier": "@webdeveric/prettier-config",
90
+ "lint-staged": {
91
+ "*.{js,ts}": "eslint --fix",
92
+ "*.{ts,js,json,md}": [
93
+ "cspell lint --no-progress --no-summary --no-must-find-files",
94
+ "prettier --write"
95
+ ]
86
96
  },
87
97
  "dependencies": {
88
98
  "lodash.clonedeep": "^4.5.0",
@@ -95,14 +105,20 @@
95
105
  "@types/lodash.escaperegexp": "^4.1.6",
96
106
  "@types/node": "^17.0.10",
97
107
  "@webdeveric/eslint-config-ts": "^0.4.1",
108
+ "@webdeveric/prettier-config": "^0.2.0",
98
109
  "core-js": "^3.11.1",
99
110
  "cspell": "^5.3.12",
100
111
  "eslint": "^8.10.0",
112
+ "eslint-config-prettier": "^8.5.0",
101
113
  "eslint-import-resolver-typescript": "^2.5.0",
102
114
  "eslint-plugin-import": "^2.25.4",
103
115
  "eslint-plugin-jest": "^26.0.0",
116
+ "eslint-plugin-prettier": "^4.0.0",
117
+ "husky": "^7.0.4",
104
118
  "jest": "^27.3.0",
105
119
  "jest-ts-webcompat-resolver": "^1.0.0",
120
+ "lint-staged": "^12.4.1",
121
+ "prettier": "^2.6.2",
106
122
  "rimraf": "^3.0.2",
107
123
  "ts-jest": "^27.0.7",
108
124
  "ts-node": "^10.6.0",
package/src/asArray.ts CHANGED
@@ -1,4 +1,3 @@
1
- export function asArray<T>( data: T | T[] ) : T[]
2
- {
3
- return Array.isArray( data ) ? data : [ data ];
1
+ export function asArray<T>(data: T | T[]): T[] {
2
+ return Array.isArray(data) ? data : [data];
4
3
  }
package/src/convert.ts CHANGED
@@ -20,7 +20,7 @@ export const convert = <Input, Output>(input: Readonly<Input>, converter: AnyCon
20
20
 
21
21
  if (typeof converter === 'object' && converter !== null) {
22
22
  return getOwnProperties(converter).reduce<Partial<Output>>((data, key) => {
23
- data[ key ] = convert(input, converter[ key ]);
23
+ data[key] = convert(input, converter[key]);
24
24
 
25
25
  return data;
26
26
  }, {}) as Output;
package/src/delay.ts CHANGED
@@ -6,15 +6,14 @@ import { getType } from './getType.js';
6
6
  *
7
7
  * {@link https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value}
8
8
  */
9
- export function delay<T>(milliseconds: number, value?: T) : Promise<T>
10
- {
11
- return new Promise( (resolve, reject) => {
12
- if ( typeof milliseconds !== 'number' ) {
13
- reject( new TypeError(`milliseconds must be a number. ${getType(milliseconds)} was provided.`) );
9
+ export function delay<T>(milliseconds: number, value?: T): Promise<T> {
10
+ return new Promise((resolve, reject) => {
11
+ if (typeof milliseconds !== 'number') {
12
+ reject(new TypeError(`milliseconds must be a number. ${getType(milliseconds)} was provided.`));
14
13
 
15
14
  return;
16
15
  }
17
16
 
18
- setTimeout( resolve, Math.max(0, Math.min(milliseconds, 2_147_483_647)), value );
19
- } );
17
+ setTimeout(resolve, Math.max(0, Math.min(milliseconds, 2_147_483_647)), value);
18
+ });
20
19
  }
@@ -1,15 +1,13 @@
1
- export function delayAnimationFrame<T>(value?: T) : Promise<typeof value>
2
- {
1
+ export function delayAnimationFrame<T>(value?: T): Promise<typeof value> {
3
2
  return new Promise(resolve => {
4
- window.requestAnimationFrame( () => resolve(value) );
3
+ window.requestAnimationFrame(() => resolve(value));
5
4
  });
6
5
  }
7
6
 
8
- export function delayAnimationFrames<T>(frames: number, value?: T): Promise<typeof value>
9
- {
10
- return new Promise( (resolve, reject) => {
11
- if ( ! Number.isInteger(frames) || frames < 1 ) {
12
- reject( new TypeError('frames must be a positive integer') );
7
+ export function delayAnimationFrames<T>(frames: number, value?: T): Promise<typeof value> {
8
+ return new Promise((resolve, reject) => {
9
+ if (!Number.isInteger(frames) || frames < 1) {
10
+ reject(new TypeError('frames must be a positive integer'));
13
11
 
14
12
  return;
15
13
  }
@@ -8,11 +8,9 @@ export function getMaxValue(...values: [NumericValue, ...NumericValue[]]): Numer
8
8
 
9
9
  assertIsNumericValueArray(values);
10
10
 
11
- return values.reduce(
12
- (high, current) => {
13
- const value = typeof current === 'string' ? Number(current) : current;
11
+ return values.reduce((high, current) => {
12
+ const value = typeof current === 'string' ? Number(current) : current;
14
13
 
15
- return value > high ? current : high;
16
- },
17
- );
14
+ return value > high ? current : high;
15
+ });
18
16
  }
@@ -8,11 +8,9 @@ export function getMinValue(...values: [NumericValue, ...NumericValue[]]): Numer
8
8
 
9
9
  assertIsNumericValueArray(values);
10
10
 
11
- return values.reduce(
12
- (low, current) => {
13
- const value = typeof current === 'string' ? Number(current) : current;
11
+ return values.reduce((low, current) => {
12
+ const value = typeof current === 'string' ? Number(current) : current;
14
13
 
15
- return value < low ? current : low;
16
- },
17
- );
14
+ return value < low ? current : low;
15
+ });
18
16
  }
@@ -1,6 +1,3 @@
1
1
  export function getOwnProperties<T, K extends keyof T>(data: T): K[] {
2
- return [
3
- ...Object.getOwnPropertyNames(data),
4
- ...Object.getOwnPropertySymbols(data),
5
- ] as K[];
2
+ return [...Object.getOwnPropertyNames(data), ...Object.getOwnPropertySymbols(data)] as K[];
6
3
  }
package/src/isEmpty.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { isLengthAware } from './type-predicate.js';
2
+
1
3
  export function isEmpty(input: unknown): boolean {
2
- if (typeof input === 'undefined' || input === null || (typeof input === 'string' && ! input.length)) {
4
+ if (typeof input === 'undefined' || input === null || (typeof input === 'string' && !input.length)) {
3
5
  return true;
4
6
  }
5
7
 
@@ -7,8 +9,12 @@ export function isEmpty(input: unknown): boolean {
7
9
  return input.length === 0;
8
10
  }
9
11
 
12
+ if (input instanceof Set || input instanceof Map) {
13
+ return input.size === 0;
14
+ }
15
+
10
16
  if (typeof input === 'object') {
11
- return Object.keys(input).length === 0;
17
+ return isLengthAware(input) ? input.length === 0 : Object.keys(input).length === 0;
12
18
  }
13
19
 
14
20
  return false;
@@ -1,19 +1,18 @@
1
1
  import { promises as dns } from 'node:dns';
2
2
  import { isIP } from 'node:net';
3
3
 
4
- export async function hostnameResolvesToIp( hostname: string, ip: string ) : Promise<boolean>
5
- {
6
- const ipVersion = isIP( ip );
4
+ export async function hostnameResolvesToIp(hostname: string, ip: string): Promise<boolean> {
5
+ const ipVersion = isIP(ip);
7
6
 
8
- if ( ! ipVersion ) {
7
+ if (!ipVersion) {
9
8
  throw new Error(`Invalid IP: ${ip}`);
10
9
  }
11
10
 
12
11
  const resolve = ipVersion === 4 ? dns.resolve4 : dns.resolve6;
13
12
 
14
- const resolved = await resolve( hostname );
13
+ const resolved = await resolve(hostname);
15
14
 
16
- return resolved.some( addr => addr === ip );
15
+ return resolved.some(addr => addr === ip);
17
16
  }
18
17
 
19
18
  /**
@@ -21,23 +20,18 @@ export async function hostnameResolvesToIp( hostname: string, ip: string ) : Pro
21
20
  *
22
21
  * @see https://en.wikipedia.org/wiki/Forward-confirmed_reverse_DNS
23
22
  */
24
- export async function fcrdns( hostname: string, ip: string ) : Promise<boolean>
25
- {
23
+ export async function fcrdns(hostname: string, ip: string): Promise<boolean> {
26
24
  const hostnames = await dns.reverse(ip);
27
25
 
28
- if ( ! hostnames.length ) {
26
+ if (!hostnames.length) {
29
27
  throw new Error(`Unable to get hostnames for ${ip}`);
30
28
  }
31
29
 
32
- if ( ! hostnames.every( name => name.endsWith( hostname ) ) ) {
30
+ if (!hostnames.every(name => name.endsWith(hostname))) {
33
31
  throw new Error(`${ip} does not belong to ${hostname}`);
34
32
  }
35
33
 
36
- const results = await Promise.all(
37
- hostnames.map(
38
- name => hostnameResolvesToIp( name, ip ),
39
- ),
40
- );
34
+ const results = await Promise.all(hostnames.map(name => hostnameResolvesToIp(name, ip)));
41
35
 
42
- return results.some( val => val );
36
+ return results.some(val => val);
43
37
  }
package/src/normalize.ts CHANGED
@@ -13,7 +13,7 @@ export type NormalizeContext<OwnerRecordType, ContextData extends AnyRecord> = {
13
13
  data: ContextData;
14
14
  };
15
15
 
16
- export type NormalizerFn<PropertyType, OwnerRecordType, ContextData extends AnyRecord = AnyRecord> = (
16
+ export type NormalizerFn<PropertyType, OwnerRecordType = unknown, ContextData extends AnyRecord = AnyRecord> = (
17
17
  input: PropertyType,
18
18
  context: NormalizeContext<OwnerRecordType, ContextData>,
19
19
  ) => PropertyType;
@@ -21,13 +21,18 @@ export type NormalizerFn<PropertyType, OwnerRecordType, ContextData extends AnyR
21
21
  export type NormalizersRecord<RecordType, OwnerRecordType, ContextData extends AnyRecord = AnyRecord> = {
22
22
  readonly [Property in keyof RecordType]?: RecordType[Property] extends Builtin
23
23
  ? NormalizerFn<RecordType[Property], OwnerRecordType, ContextData>
24
- : AnyNormalizer<RecordType[Property], OwnerRecordType, ContextData>
24
+ : AnyNormalizer<RecordType[Property], OwnerRecordType, ContextData>;
25
25
  };
26
26
 
27
27
  export type AnyNormalizer<RecordType, OwnerRecordType, ContextData extends AnyRecord = AnyRecord> =
28
28
  | NormalizerFn<RecordType, OwnerRecordType, ContextData>
29
29
  | NormalizersRecord<RecordType, OwnerRecordType, ContextData>;
30
30
 
31
+ export type ContextInitializer<OwnerRecordType, ContextData extends AnyRecord = AnyRecord> = (
32
+ data: OwnerRecordType,
33
+ normalizers: AnyNormalizer<OwnerRecordType, OwnerRecordType, ContextData>,
34
+ ) => ContextData;
35
+
31
36
  /**
32
37
  * @example
33
38
  *
@@ -45,8 +50,19 @@ export type AnyNormalizer<RecordType, OwnerRecordType, ContextData extends AnyRe
45
50
  */
46
51
  export function normalize<Data, ContextData extends AnyRecord = AnyRecord>(
47
52
  input: Readonly<Data>,
48
- normalizers?: AnyNormalizer<Data, Data, ContextData>,
49
- initContextData: (data: typeof input, dataNormalizers: typeof normalizers) => ContextData = (): AnyRecord => ({}),
53
+ normalizers: AnyNormalizer<Data, Data, Partial<ContextData>>, // No initializer so data must be partial
54
+ ): Data;
55
+
56
+ export function normalize<Data, ContextData extends AnyRecord = AnyRecord>(
57
+ input: Readonly<Data>,
58
+ normalizers: AnyNormalizer<Data, Data, ContextData>,
59
+ initContextData: ContextInitializer<Data, ContextData>,
60
+ ): Data;
61
+
62
+ export function normalize<Data, ContextData extends AnyRecord = AnyRecord>(
63
+ input: Readonly<Data>,
64
+ normalizers: AnyNormalizer<Data, Data, ContextData>,
65
+ initContextData: ContextInitializer<Data, ContextData> = (): AnyRecord => ({}),
50
66
  ): Data {
51
67
  const current = cloneDeep(input);
52
68
 
@@ -67,13 +83,14 @@ export function normalize<Data, ContextData extends AnyRecord = AnyRecord>(
67
83
  if (typeof currentNormalizers === 'object' && currentNormalizers !== null) {
68
84
  if (typeof currentRecord === 'object' && currentRecord !== null) {
69
85
  return getOwnProperties(currentNormalizers).reduce((data, key) => {
70
- const normalizers = currentNormalizers[ key ];
86
+ const normalizers = currentNormalizers[key];
71
87
  // If the value is undefined but there is a normalizer record, set value to empty object.
72
- const value = typeof data[ key ] === 'undefined' && isObject(normalizers)
73
- ? {} as CurrentRecord[keyof CurrentRecord]
74
- : data[ key ];
88
+ const value =
89
+ typeof data[key] === 'undefined' && isObject(normalizers)
90
+ ? ({} as unknown as CurrentRecord[keyof CurrentRecord])
91
+ : data[key];
75
92
 
76
- data[ key ] = walk(value, normalizers);
93
+ data[key] = walk(value, normalizers);
77
94
 
78
95
  return data;
79
96
  }, currentRecord);
@@ -15,33 +15,30 @@ type SecondsTuple = [key: Lowercase<keyof typeof Seconds>, seconds: Seconds];
15
15
 
16
16
  export function secToString(time: number, joinString = ' '): string {
17
17
  const secTime: SecondsTuple[] = [
18
- [ 'millennium', Seconds.Millennium ],
19
- [ 'century', Seconds.Century ],
20
- [ 'decade', Seconds.Decade ],
21
- [ 'year', Seconds.Year ],
22
- [ 'month', Seconds.Month ],
23
- [ 'week', Seconds.Week ],
24
- [ 'day', Seconds.Day ],
25
- [ 'hour', Seconds.Hour ],
26
- [ 'minute', Seconds.Minute ],
27
- [ 'second', Seconds.Second ],
18
+ ['millennium', Seconds.Millennium],
19
+ ['century', Seconds.Century],
20
+ ['decade', Seconds.Decade],
21
+ ['year', Seconds.Year],
22
+ ['month', Seconds.Month],
23
+ ['week', Seconds.Week],
24
+ ['day', Seconds.Day],
25
+ ['hour', Seconds.Hour],
26
+ ['minute', Seconds.Minute],
27
+ ['second', Seconds.Second],
28
28
  ];
29
29
 
30
- const parts = secTime.reduce<string[]>(
31
- (output, [ units, seconds ]) => {
32
- if (seconds <= time) {
33
- const currentValue = Math.floor(time / seconds);
34
- const suffix = currentValue === 1 ? units : `${units}s`;
30
+ const parts = secTime.reduce<string[]>((output, [units, seconds]) => {
31
+ if (seconds <= time) {
32
+ const currentValue = Math.floor(time / seconds);
33
+ const suffix = currentValue === 1 ? units : `${units}s`;
35
34
 
36
- time %= seconds;
35
+ time %= seconds;
37
36
 
38
- output.push(`${currentValue} ${suffix}`);
39
- }
37
+ output.push(`${currentValue} ${suffix}`);
38
+ }
40
39
 
41
- return output;
42
- },
43
- [],
44
- );
40
+ return output;
41
+ }, []);
45
42
 
46
43
  // cSpell:ignore centurys
47
44
  return parts.join(joinString).replace('centurys', 'centuries');
@@ -1,32 +1,28 @@
1
1
  import { getType } from './getType.js';
2
2
 
3
- export function toPascalCase(text: string, customWords?: Record<string, string>) : string
4
- {
5
- let words = String(text).match( /[A-Z][a-z']+|\d+|[a-z']+/g );
3
+ export function toPascalCase(text: string, customWords?: Record<string, string>): string {
4
+ let words = String(text).match(/[A-Z][a-z']+|\d+|[a-z']+/g);
6
5
 
7
- if ( ! words ) {
6
+ if (!words) {
8
7
  return '';
9
8
  }
10
9
 
11
10
  // Remove apostrophes then uppercase the first letter of each word.
12
- words = words.map( word => {
11
+ words = words.map(word => {
13
12
  const fixedWord = word.replace(/'/g, '');
14
13
 
15
14
  return fixedWord.substring(0, 1).toUpperCase() + fixedWord.substring(1);
16
15
  });
17
16
 
18
- if ( customWords && getType(customWords) === 'Object' ) {
19
- const replacements = Object.entries( customWords ).map(([ key, value ]) => [
20
- key.toLowerCase(),
21
- value,
22
- ]);
17
+ if (customWords && getType(customWords) === 'Object') {
18
+ const replacements = Object.entries(customWords).map(([key, value]) => [key.toLowerCase(), value]);
23
19
 
24
- if ( replacements.length ) {
20
+ if (replacements.length) {
25
21
  // This takes a single word and returns the first matching replacement, if any.
26
- const replaceCustomWords = (word: string) : string => {
22
+ const replaceCustomWords = (word: string): string => {
27
23
  const lowerWord = word.toLowerCase();
28
24
 
29
- for (const [ key, value ] of replacements) {
25
+ for (const [key, value] of replacements) {
30
26
  if (key === lowerWord && typeof value === 'string') {
31
27
  return value;
32
28
  }
@@ -2,19 +2,19 @@ import { isNumericValueArray } from './type-predicate.js';
2
2
  import type { NumericValue } from './types';
3
3
 
4
4
  export function assertIsInteger(input: unknown): asserts input is number {
5
- if (! Number.isInteger(input)) {
5
+ if (!Number.isInteger(input)) {
6
6
  throw new TypeError('input is not an integer');
7
7
  }
8
8
  }
9
9
 
10
10
  export function assertIsFiniteNumber(input: unknown): asserts input is number {
11
- if (! Number.isFinite(input)) {
11
+ if (!Number.isFinite(input)) {
12
12
  throw new TypeError('input is not a finite number');
13
13
  }
14
14
  }
15
15
 
16
16
  export function assertIsNumericValueArray(input: unknown): asserts input is NumericValue[] {
17
- if (! isNumericValueArray(input)) {
17
+ if (!isNumericValueArray(input)) {
18
18
  throw new TypeError('all items must be a NumericValue');
19
19
  }
20
20
  }
@@ -4,7 +4,7 @@ export const isOptionalString = (input: unknown): input is string | undefined =>
4
4
  typeof input === 'string' || typeof input === 'undefined';
5
5
 
6
6
  export const isOptionalNumber = (input: unknown): input is number | undefined =>
7
- (typeof input === 'number' && ! Number.isNaN(input)) || typeof input === 'undefined';
7
+ (typeof input === 'number' && !Number.isNaN(input)) || typeof input === 'undefined';
8
8
 
9
9
  export const isStringMatching = (input: unknown, pattern: RegExp): input is string =>
10
10
  typeof input === 'string' && pattern.test(input);
@@ -30,3 +30,7 @@ export const isInteger = (input: unknown): input is number => Number.isInteger(i
30
30
  export const isPositiveInteger = (input: unknown): input is number => isInteger(input) && input >= 0;
31
31
 
32
32
  export const isPositiveFiniteNumber = (input: unknown): input is number => isFiniteNumber(input) && input >= 0;
33
+
34
+ export const isLengthAware = (input: unknown): input is { length: number } =>
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
+ typeof input === 'object' && input !== null && 'length' in input && typeof (input as any).length === 'number';
package/src/types.ts CHANGED
@@ -10,3 +10,10 @@ export type NumericValue = number | bigint | NumericString;
10
10
  export type MaybePlural<T extends string> = T | `${T}s`;
11
11
 
12
12
  export type StringKeys<T> = keyof T & string;
13
+
14
+ export type IfDefined<T, D, U> = undefined extends T ? U : D;
15
+
16
+ export type IfNever<T, N, O> = [T] extends [never] ? N : O;
17
+
18
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
+ export type ReturnTypeDefault<F, D = undefined> = F extends (...args: any) => infer R ? R : D;
@@ -1,4 +1,3 @@
1
- export function uniqueItems<T>( data: T[] ) : T[]
2
- {
3
- return [ ...new Set<T>( data ) ];
1
+ export function uniqueItems<T>(data: T[]): T[] {
2
+ return [...new Set<T>(data)];
4
3
  }
package/src/until.ts CHANGED
@@ -33,35 +33,35 @@ const defaultOptions: Readonly<UntilOptions> = {
33
33
  /**
34
34
  * Return a Promise that delegates resolving/rejecting to the passed in function.
35
35
  */
36
- export function until<T>( fn: UntilCallback<T>, options: UntilOptions = defaultOptions ) : Promise<T>
37
- {
38
- if ( typeof fn !== 'function' ) {
36
+ export function until<T>(fn: UntilCallback<T>, options: UntilOptions = defaultOptions): Promise<T> {
37
+ if (typeof fn !== 'function') {
39
38
  return Promise.reject(new Error('fn must be a function'));
40
39
  }
41
40
 
42
- if ( ! options || typeof options !== 'object' ) {
41
+ if (!options || typeof options !== 'object') {
43
42
  return Promise.reject(new Error(`options must be an object. ${getType(options)} provided.`));
44
43
  }
45
44
 
46
45
  const { delay, timeout, callLimit } = Object.assign({}, defaultOptions, options);
47
46
 
48
- const isDelay = ( input: unknown ) : input is Delay => Number.isInteger( input ) || typeof input === 'function';
47
+ const isDelay = (input: unknown): input is Delay => Number.isInteger(input) || typeof input === 'function';
49
48
 
50
- const getDelay = ( delay: Delay, context: UntilContext ) : number => typeof delay === 'function' ? delay( context ) : delay;
49
+ const getDelay = (delay: Delay, context: UntilContext): number =>
50
+ typeof delay === 'function' ? delay(context) : delay;
51
51
 
52
- if ( ! isDelay( delay ) ) {
52
+ if (!isDelay(delay)) {
53
53
  return Promise.reject(new Error('invalid delay value'));
54
54
  }
55
55
 
56
- if ( timeout !== undefined && ! isDelay( timeout ) ) {
56
+ if (timeout !== undefined && !isDelay(timeout)) {
57
57
  return Promise.reject(new Error('invalid timeout value'));
58
58
  }
59
59
 
60
- if ( callLimit !== undefined && ! Number.isInteger( callLimit ) ) {
60
+ if (callLimit !== undefined && !Number.isInteger(callLimit)) {
61
61
  return Promise.reject(new Error('invalid callLimit value'));
62
62
  }
63
63
 
64
- return new Promise<T>( ( resolutionFn: ResolveFn<T>, rejectionFn: RejectFn ) => {
64
+ return new Promise<T>((resolutionFn: ResolveFn<T>, rejectionFn: RejectFn) => {
65
65
  let callCount = 0;
66
66
  let lastCall: number | undefined;
67
67
  let done = false;
@@ -70,19 +70,19 @@ export function until<T>( fn: UntilCallback<T>, options: UntilOptions = defaultO
70
70
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
71
71
  let timeoutTimer: any;
72
72
 
73
- const finish = () : void => {
73
+ const finish = (): void => {
74
74
  done = true;
75
- clearTimeout( timer );
76
- clearTimeout( timeoutTimer );
75
+ clearTimeout(timer);
76
+ clearTimeout(timeoutTimer);
77
77
  };
78
78
 
79
- const resolve: ResolveFn<T> = (value: ResolverValue<T>) : void => {
80
- resolutionFn( value );
79
+ const resolve: ResolveFn<T> = (value: ResolverValue<T>): void => {
80
+ resolutionFn(value);
81
81
  finish();
82
82
  };
83
83
 
84
- const reject: RejectFn = (error?: Error) : void => {
85
- rejectionFn( error );
84
+ const reject: RejectFn = (error?: Error): void => {
85
+ rejectionFn(error);
86
86
  finish();
87
87
  };
88
88
 
@@ -99,35 +99,32 @@ export function until<T>( fn: UntilCallback<T>, options: UntilOptions = defaultO
99
99
  data: {},
100
100
  });
101
101
 
102
- const callUntilDone = ( fn: UntilCallback<T>, delay: Delay, resolve: ResolveFn<T>, reject: RejectFn ) : void => {
102
+ const callUntilDone = (fn: UntilCallback<T>, delay: Delay, resolve: ResolveFn<T>, reject: RejectFn): void => {
103
103
  try {
104
- if ( callLimit && callCount >= callLimit ) {
104
+ if (callLimit && callCount >= callLimit) {
105
105
  throw new Error(`until callLimit reached: ${callLimit}`);
106
106
  }
107
107
 
108
108
  ++callCount;
109
109
 
110
- fn( resolve, reject, context );
110
+ fn(resolve, reject, context);
111
111
 
112
112
  lastCall = Date.now();
113
113
 
114
- if ( ! done ) {
115
- timer = setTimeout( callUntilDone, getDelay( delay, context ), fn, delay, resolve, reject );
114
+ if (!done) {
115
+ timer = setTimeout(callUntilDone, getDelay(delay, context), fn, delay, resolve, reject);
116
116
  }
117
- } catch ( error ) {
118
- reject( error instanceof Error ? error : new Error(`${error}`) );
117
+ } catch (error) {
118
+ reject(error instanceof Error ? error : new Error(`${error}`));
119
119
  }
120
120
  };
121
121
 
122
- callUntilDone( fn, delay, resolve, reject );
122
+ callUntilDone(fn, delay, resolve, reject);
123
123
 
124
- if ( ! done && timeout !== undefined ) {
125
- timeoutTimer = setTimeout(
126
- () => {
127
- reject( new Error('until: timed out') );
128
- },
129
- getDelay( timeout, context ),
130
- );
124
+ if (!done && timeout !== undefined) {
125
+ timeoutTimer = setTimeout(() => {
126
+ reject(new Error('until: timed out'));
127
+ }, getDelay(timeout, context));
131
128
  }
132
129
  });
133
130
  }