@webdeveric/utils 0.11.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 (118) hide show
  1. package/dist/cjs/asArray.js.map +1 -1
  2. package/dist/cjs/clamp.js +10 -0
  3. package/dist/cjs/clamp.js.map +1 -0
  4. package/dist/cjs/convert.js.map +1 -1
  5. package/dist/cjs/delay.js.map +1 -1
  6. package/dist/cjs/delayAnimationFrame.js.map +1 -1
  7. package/dist/cjs/getMaxValue.js +16 -0
  8. package/dist/cjs/getMaxValue.js.map +1 -0
  9. package/dist/cjs/getMinValue.js +16 -0
  10. package/dist/cjs/getMinValue.js.map +1 -0
  11. package/dist/cjs/getOwnProperties.js +1 -4
  12. package/dist/cjs/getOwnProperties.js.map +1 -1
  13. package/dist/cjs/index.js +11 -1
  14. package/dist/cjs/index.js.map +1 -1
  15. package/dist/cjs/isEmpty.js +5 -1
  16. package/dist/cjs/isEmpty.js.map +1 -1
  17. package/dist/cjs/isObject.js +8 -0
  18. package/dist/cjs/isObject.js.map +1 -0
  19. package/dist/cjs/node/fcrdns.js.map +1 -1
  20. package/dist/cjs/node/index.js +5 -1
  21. package/dist/cjs/node/index.js.map +1 -1
  22. package/dist/cjs/normalize.js +12 -28
  23. package/dist/cjs/normalize.js.map +1 -1
  24. package/dist/cjs/secToString.js.map +1 -1
  25. package/dist/cjs/toPascalCase.js +3 -6
  26. package/dist/cjs/toPascalCase.js.map +1 -1
  27. package/dist/cjs/type-assertion.js +23 -0
  28. package/dist/cjs/type-assertion.js.map +1 -0
  29. package/dist/cjs/type-predicate.js +32 -0
  30. package/dist/cjs/type-predicate.js.map +1 -0
  31. package/dist/cjs/types.js +3 -0
  32. package/dist/cjs/types.js.map +1 -0
  33. package/dist/cjs/uniqueItems.js.map +1 -1
  34. package/dist/cjs/until.js.map +1 -1
  35. package/dist/mjs/asArray.js.map +1 -1
  36. package/dist/mjs/clamp.js +6 -0
  37. package/dist/mjs/clamp.js.map +1 -0
  38. package/dist/mjs/compose.js +1 -2
  39. package/dist/mjs/compose.js.map +1 -1
  40. package/dist/mjs/convert.js.map +1 -1
  41. package/dist/mjs/delay.js.map +1 -1
  42. package/dist/mjs/delayAnimationFrame.js.map +1 -1
  43. package/dist/mjs/getMaxValue.js +12 -0
  44. package/dist/mjs/getMaxValue.js.map +1 -0
  45. package/dist/mjs/getMinValue.js +12 -0
  46. package/dist/mjs/getMinValue.js.map +1 -0
  47. package/dist/mjs/getOwnProperties.js +1 -4
  48. package/dist/mjs/getOwnProperties.js.map +1 -1
  49. package/dist/mjs/index.js +6 -0
  50. package/dist/mjs/index.js.map +1 -1
  51. package/dist/mjs/isEmpty.js +5 -1
  52. package/dist/mjs/isEmpty.js.map +1 -1
  53. package/dist/mjs/isObject.js +4 -0
  54. package/dist/mjs/isObject.js.map +1 -0
  55. package/dist/mjs/node/fcrdns.js.map +1 -1
  56. package/dist/mjs/normalize.js +12 -28
  57. package/dist/mjs/normalize.js.map +1 -1
  58. package/dist/mjs/secToString.js.map +1 -1
  59. package/dist/mjs/toPascalCase.js +3 -6
  60. package/dist/mjs/toPascalCase.js.map +1 -1
  61. package/dist/mjs/type-assertion.js +17 -0
  62. package/dist/mjs/type-assertion.js.map +1 -0
  63. package/dist/mjs/type-predicate.js +16 -0
  64. package/dist/mjs/type-predicate.js.map +1 -0
  65. package/dist/mjs/types.js +2 -0
  66. package/dist/mjs/types.js.map +1 -0
  67. package/dist/mjs/uniqueItems.js.map +1 -1
  68. package/dist/mjs/until.js.map +1 -1
  69. package/dist/types/asArray.d.ts.map +1 -1
  70. package/dist/types/clamp.d.ts +3 -0
  71. package/dist/types/clamp.d.ts.map +1 -0
  72. package/dist/types/delay.d.ts.map +1 -1
  73. package/dist/types/delayAnimationFrame.d.ts.map +1 -1
  74. package/dist/types/getMaxValue.d.ts +3 -0
  75. package/dist/types/getMaxValue.d.ts.map +1 -0
  76. package/dist/types/getMinValue.d.ts +3 -0
  77. package/dist/types/getMinValue.d.ts.map +1 -0
  78. package/dist/types/getOwnProperties.d.ts.map +1 -1
  79. package/dist/types/index.d.ts +6 -0
  80. package/dist/types/index.d.ts.map +1 -1
  81. package/dist/types/isEmpty.d.ts.map +1 -1
  82. package/dist/types/isObject.d.ts +2 -0
  83. package/dist/types/isObject.d.ts.map +1 -0
  84. package/dist/types/node/fcrdns.d.ts.map +1 -1
  85. package/dist/types/normalize.d.ts +10 -6
  86. package/dist/types/normalize.d.ts.map +1 -1
  87. package/dist/types/secToString.d.ts.map +1 -1
  88. package/dist/types/toPascalCase.d.ts.map +1 -1
  89. package/dist/types/type-assertion.d.ts +5 -0
  90. package/dist/types/type-assertion.d.ts.map +1 -0
  91. package/dist/types/type-predicate.d.ts +17 -0
  92. package/dist/types/type-predicate.d.ts.map +1 -0
  93. package/dist/types/types.d.ts +10 -0
  94. package/dist/types/types.d.ts.map +1 -0
  95. package/dist/types/uniqueItems.d.ts.map +1 -1
  96. package/dist/types/until.d.ts +2 -1
  97. package/dist/types/until.d.ts.map +1 -1
  98. package/package.json +30 -7
  99. package/src/asArray.ts +2 -3
  100. package/src/clamp.ts +7 -0
  101. package/src/convert.ts +1 -1
  102. package/src/delay.ts +6 -7
  103. package/src/delayAnimationFrame.ts +6 -8
  104. package/src/getMaxValue.ts +16 -0
  105. package/src/getMinValue.ts +16 -0
  106. package/src/getOwnProperties.ts +1 -4
  107. package/src/index.ts +6 -0
  108. package/src/isEmpty.ts +8 -2
  109. package/src/isObject.ts +3 -0
  110. package/src/node/fcrdns.ts +10 -16
  111. package/src/normalize.ts +51 -27
  112. package/src/secToString.ts +19 -22
  113. package/src/toPascalCase.ts +11 -15
  114. package/src/type-assertion.ts +20 -0
  115. package/src/type-predicate.ts +36 -0
  116. package/src/types.ts +19 -0
  117. package/src/uniqueItems.ts +2 -3
  118. package/src/until.ts +31 -34
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
  }
@@ -0,0 +1,16 @@
1
+ import { assertIsNumericValueArray } from './type-assertion.js';
2
+ import type { NumericValue } from './types';
3
+
4
+ export function getMaxValue(...values: [NumericValue, ...NumericValue[]]): NumericValue {
5
+ if (values.length === 0) {
6
+ throw new Error('Expected at least one numeric value');
7
+ }
8
+
9
+ assertIsNumericValueArray(values);
10
+
11
+ return values.reduce((high, current) => {
12
+ const value = typeof current === 'string' ? Number(current) : current;
13
+
14
+ return value > high ? current : high;
15
+ });
16
+ }
@@ -0,0 +1,16 @@
1
+ import { assertIsNumericValueArray } from './type-assertion.js';
2
+ import type { NumericValue } from './types';
3
+
4
+ export function getMinValue(...values: [NumericValue, ...NumericValue[]]): NumericValue {
5
+ if (values.length === 0) {
6
+ throw new Error('Expected at least one numeric value');
7
+ }
8
+
9
+ assertIsNumericValueArray(values);
10
+
11
+ return values.reduce((low, current) => {
12
+ const value = typeof current === 'string' ? Number(current) : current;
13
+
14
+ return value < low ? current : low;
15
+ });
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/index.ts CHANGED
@@ -1,17 +1,23 @@
1
1
  export * from './asArray.js';
2
+ export * from './clamp.js';
2
3
  export * from './compose.js';
3
4
  export * from './convert.js';
4
5
  export * from './delay.js';
5
6
  export * from './delayAnimationFrame.js';
7
+ export * from './getMaxValue.js';
8
+ export * from './getMinValue.js';
6
9
  export * from './getOwnKeys.js';
7
10
  export * from './getOwnProperties.js';
8
11
  export * from './getType.js';
9
12
  export * from './isEmpty.js';
13
+ export * from './isObject.js';
10
14
  export * from './joinStrings.js';
11
15
  export * from './normalize.js';
12
16
  export * from './secToString.js';
13
17
  export * from './toPascalCase.js';
14
18
  export * from './trimEnd.js';
15
19
  export * from './trimStart.js';
20
+ export * from './type-assertion.js';
21
+ export * from './types.js';
16
22
  export * from './uniqueItems.js';
17
23
  export * from './until.js';
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;
@@ -0,0 +1,3 @@
1
+ export function isObject(input: unknown): boolean {
2
+ return typeof input === 'object' && input !== null;
3
+ }
@@ -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
@@ -3,25 +3,36 @@ import cloneDeep from 'lodash.clonedeep';
3
3
  import type { Builtin } from 'ts-essentials';
4
4
 
5
5
  import { getOwnProperties } from './getOwnProperties.js';
6
- import { getType } from './getType.js';
6
+ import { isObject } from './isObject.js';
7
7
 
8
- export type NormalizeContext<OwnerRecordType> = {
8
+ import type { AnyRecord } from './types';
9
+
10
+ export type NormalizeContext<OwnerRecordType, ContextData extends AnyRecord> = {
9
11
  original: Readonly<OwnerRecordType>;
10
12
  current: OwnerRecordType;
11
- data: Record<PropertyKey, unknown>;
13
+ data: ContextData;
12
14
  };
13
15
 
14
- export type NormalizerFn<OutputType, OwnerRecordType> = (
15
- input: unknown,
16
- context: NormalizeContext<OwnerRecordType>,
17
- ) => OutputType;
16
+ export type NormalizerFn<PropertyType, OwnerRecordType = unknown, ContextData extends AnyRecord = AnyRecord> = (
17
+ input: PropertyType,
18
+ context: NormalizeContext<OwnerRecordType, ContextData>,
19
+ ) => PropertyType;
18
20
 
19
- export type NormalizersRecord<RecordType, OwnerRecordType = RecordType> = {
20
- [Property in keyof RecordType]?: RecordType[Property] extends Builtin
21
- ? NormalizerFn<RecordType[Property], OwnerRecordType>
22
- : NormalizerFn<RecordType[Property], OwnerRecordType> | NormalizersRecord<RecordType[Property], OwnerRecordType>;
21
+ export type NormalizersRecord<RecordType, OwnerRecordType, ContextData extends AnyRecord = AnyRecord> = {
22
+ readonly [Property in keyof RecordType]?: RecordType[Property] extends Builtin
23
+ ? NormalizerFn<RecordType[Property], OwnerRecordType, ContextData>
24
+ : AnyNormalizer<RecordType[Property], OwnerRecordType, ContextData>;
23
25
  };
24
26
 
27
+ export type AnyNormalizer<RecordType, OwnerRecordType, ContextData extends AnyRecord = AnyRecord> =
28
+ | NormalizerFn<RecordType, OwnerRecordType, ContextData>
29
+ | NormalizersRecord<RecordType, OwnerRecordType, ContextData>;
30
+
31
+ export type ContextInitializer<OwnerRecordType, ContextData extends AnyRecord = AnyRecord> = (
32
+ data: OwnerRecordType,
33
+ normalizers: AnyNormalizer<OwnerRecordType, OwnerRecordType, ContextData>,
34
+ ) => ContextData;
35
+
25
36
  /**
26
37
  * @example
27
38
  *
@@ -37,26 +48,34 @@ export type NormalizersRecord<RecordType, OwnerRecordType = RecordType> = {
37
48
  * normalize(true, () => false );
38
49
  * ```
39
50
  */
40
- export function normalize<Data>(
41
- input: Data,
42
- normalizers?: NormalizerFn<Data, Data> | NormalizersRecord<Data, Data>,
51
+ export function normalize<Data, ContextData extends AnyRecord = AnyRecord>(
52
+ input: Readonly<Data>,
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 => ({}),
43
66
  ): Data {
44
- const normalized = cloneDeep(input);
67
+ const current = cloneDeep(input);
45
68
 
46
- const context: NormalizeContext<Data> = Object.seal({
69
+ const context: NormalizeContext<Data, ContextData> = Object.seal({
47
70
  original: input,
48
- current: normalized,
49
- data: {},
71
+ current,
72
+ data: initContextData(input, normalizers),
50
73
  });
51
74
 
52
75
  const walk = <CurrentRecord>(
53
76
  currentRecord: CurrentRecord,
54
- currentNormalizers?: NormalizerFn<CurrentRecord, Data> | NormalizersRecord<CurrentRecord, Data>,
77
+ currentNormalizers?: AnyNormalizer<CurrentRecord, Data, ContextData>,
55
78
  ): CurrentRecord => {
56
- if (typeof currentNormalizers === 'undefined') {
57
- return currentRecord;
58
- }
59
-
60
79
  if (typeof currentNormalizers === 'function') {
61
80
  return currentNormalizers(currentRecord, context);
62
81
  }
@@ -64,17 +83,22 @@ export function normalize<Data>(
64
83
  if (typeof currentNormalizers === 'object' && currentNormalizers !== null) {
65
84
  if (typeof currentRecord === 'object' && currentRecord !== null) {
66
85
  return getOwnProperties(currentNormalizers).reduce((data, key) => {
67
- data[ key ] = walk(data[ key ], currentNormalizers[ key ]);
86
+ const normalizers = currentNormalizers[key];
87
+ // If the value is undefined but there is a normalizer record, set value to empty object.
88
+ const value =
89
+ typeof data[key] === 'undefined' && isObject(normalizers)
90
+ ? ({} as unknown as CurrentRecord[keyof CurrentRecord])
91
+ : data[key];
92
+
93
+ data[key] = walk(value, normalizers);
68
94
 
69
95
  return data;
70
96
  }, currentRecord);
71
97
  }
72
- } else {
73
- throw new TypeError(`normalizers must be function or object. ${getType(currentNormalizers)} was received.`);
74
98
  }
75
99
 
76
100
  return currentRecord;
77
101
  };
78
102
 
79
- return walk(normalized, normalizers);
103
+ return walk(current, normalizers);
80
104
  }
@@ -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,33 +1,29 @@
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
- return fixedWord[ 0 ].toUpperCase() + fixedWord.substring(1);
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) {
30
- if (key === lowerWord) {
25
+ for (const [key, value] of replacements) {
26
+ if (key === lowerWord && typeof value === 'string') {
31
27
  return value;
32
28
  }
33
29
  }
@@ -0,0 +1,20 @@
1
+ import { isNumericValueArray } from './type-predicate.js';
2
+ import type { NumericValue } from './types';
3
+
4
+ export function assertIsInteger(input: unknown): asserts input is number {
5
+ if (!Number.isInteger(input)) {
6
+ throw new TypeError('input is not an integer');
7
+ }
8
+ }
9
+
10
+ export function assertIsFiniteNumber(input: unknown): asserts input is number {
11
+ if (!Number.isFinite(input)) {
12
+ throw new TypeError('input is not a finite number');
13
+ }
14
+ }
15
+
16
+ export function assertIsNumericValueArray(input: unknown): asserts input is NumericValue[] {
17
+ if (!isNumericValueArray(input)) {
18
+ throw new TypeError('all items must be a NumericValue');
19
+ }
20
+ }
@@ -0,0 +1,36 @@
1
+ import type { NumericString, NumericValue } from './types';
2
+
3
+ export const isOptionalString = (input: unknown): input is string | undefined =>
4
+ typeof input === 'string' || typeof input === 'undefined';
5
+
6
+ export const isOptionalNumber = (input: unknown): input is number | undefined =>
7
+ (typeof input === 'number' && !Number.isNaN(input)) || typeof input === 'undefined';
8
+
9
+ export const isStringMatching = (input: unknown, pattern: RegExp): input is string =>
10
+ typeof input === 'string' && pattern.test(input);
11
+
12
+ export const isPropertyKey = (input: unknown): input is PropertyKey =>
13
+ typeof input === 'string' || typeof input === 'number' || typeof input === 'symbol';
14
+
15
+ export const isNumericString = (input: unknown): input is NumericString =>
16
+ isStringMatching(input, /^[-+]?\d+(\.\d+)?$/);
17
+
18
+ export const isNumericValue = (input: unknown): input is NumericValue =>
19
+ typeof input === 'number' || typeof input === 'bigint' || isNumericString(input);
20
+
21
+ export const isNumericValueArray = (input: unknown): input is NumericValue[] =>
22
+ Array.isArray(input) && input.every(isNumericValue);
23
+
24
+ export const isIntString = (input: unknown): input is NumericString => isStringMatching(input, /^[-+]?\d+$/);
25
+
26
+ export const isFiniteNumber = (input: unknown): input is number => typeof input === 'number' && Number.isFinite(input);
27
+
28
+ export const isInteger = (input: unknown): input is number => Number.isInteger(input);
29
+
30
+ export const isPositiveInteger = (input: unknown): input is number => isInteger(input) && input >= 0;
31
+
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 ADDED
@@ -0,0 +1,19 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2
+ export type AnyRecord = Record<PropertyKey, any>;
3
+
4
+ export type UnknownRecord = Record<PropertyKey, unknown>;
5
+
6
+ export type NumericString<T extends string | number = number> = `${T}` extends `${number}` ? `${T}` : never;
7
+
8
+ export type NumericValue = number | bigint | NumericString;
9
+
10
+ export type MaybePlural<T extends string> = T | `${T}s`;
11
+
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
@@ -1,10 +1,10 @@
1
+ import type { AnyRecord } from './types';
1
2
  import { getType } from './getType.js';
2
3
 
3
4
  export interface UntilContext {
4
5
  callCount: number;
5
6
  lastCall?: number;
6
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
- data: Record<PropertyKey, any>;
7
+ data: AnyRecord;
8
8
  options: UntilOptions;
9
9
  }
10
10
 
@@ -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
  }