@webdeveric/utils 0.18.0 → 0.20.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 (50) hide show
  1. package/dist/cjs/type-assertion.js +185 -10
  2. package/dist/cjs/type-assertion.js.map +1 -1
  3. package/dist/cjs/type-predicate-factory.js +19 -0
  4. package/dist/cjs/type-predicate-factory.js.map +1 -0
  5. package/dist/cjs/type-predicate.js +53 -20
  6. package/dist/cjs/type-predicate.js.map +1 -1
  7. package/dist/mjs/type-assertion.js +155 -9
  8. package/dist/mjs/type-assertion.js.map +1 -1
  9. package/dist/mjs/type-predicate-factory.js +11 -0
  10. package/dist/mjs/type-predicate-factory.js.map +1 -0
  11. package/dist/mjs/type-predicate.js +38 -14
  12. package/dist/mjs/type-predicate.js.map +1 -1
  13. package/dist/types/type-assertion.d.ts +35 -4
  14. package/dist/types/type-assertion.d.ts.map +1 -1
  15. package/dist/types/type-predicate-factory.d.ts +7 -0
  16. package/dist/types/type-predicate-factory.d.ts.map +1 -0
  17. package/dist/types/type-predicate.d.ts +21 -6
  18. package/dist/types/type-predicate.d.ts.map +1 -1
  19. package/dist/types/types.d.ts +2 -0
  20. package/dist/types/types.d.ts.map +1 -1
  21. package/package.json +23 -22
  22. package/src/asArray.ts +0 -3
  23. package/src/capitalize.ts +0 -1
  24. package/src/clamp.ts +0 -7
  25. package/src/compose.ts +0 -13
  26. package/src/convert.ts +0 -30
  27. package/src/delay.ts +0 -23
  28. package/src/delayAnimationFrame.ts +0 -35
  29. package/src/getMaxValue.ts +0 -16
  30. package/src/getMinValue.ts +0 -16
  31. package/src/getOwnKeys.ts +0 -3
  32. package/src/getOwnProperties.ts +0 -3
  33. package/src/getType.ts +0 -3
  34. package/src/index.ts +0 -24
  35. package/src/isEmpty.ts +0 -21
  36. package/src/isObject.ts +0 -3
  37. package/src/joinStrings.ts +0 -6
  38. package/src/node/fcrdns.ts +0 -37
  39. package/src/node/index.ts +0 -1
  40. package/src/normalize.ts +0 -102
  41. package/src/secToString.ts +0 -45
  42. package/src/toPascalCase.ts +0 -29
  43. package/src/trimEnd.ts +0 -5
  44. package/src/trimIndentation.ts +0 -18
  45. package/src/trimStart.ts +0 -5
  46. package/src/type-assertion.ts +0 -20
  47. package/src/type-predicate.ts +0 -48
  48. package/src/types.ts +0 -42
  49. package/src/uniqueItems.ts +0 -3
  50. package/src/until.ts +0 -130
@@ -1,45 +0,0 @@
1
- export enum Seconds {
2
- Second = 1,
3
- Minute = 60 * Second,
4
- Hour = 60 * Minute,
5
- Day = 24 * Hour,
6
- Week = 7 * Day,
7
- Month = (365.25 / 12) * Day,
8
- Year = 12 * Month,
9
- Decade = 10 * Year,
10
- Century = 10 * Decade,
11
- Millennium = 10 * Century,
12
- }
13
-
14
- type SecondsTuple = [key: Lowercase<keyof typeof Seconds>, seconds: Seconds];
15
-
16
- export function secToString(time: number, joinString = ' '): string {
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],
28
- ];
29
-
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`;
34
-
35
- time %= seconds;
36
-
37
- output.push(`${currentValue} ${suffix}`);
38
- }
39
-
40
- return output;
41
- }, []);
42
-
43
- // cSpell:ignore centurys
44
- return parts.join(joinString).replace('centurys', 'centuries');
45
- }
@@ -1,29 +0,0 @@
1
- import { capitalize } from './capitalize.js';
2
- import { getType } from './getType.js';
3
-
4
- import type { KeyValueTuple, StringRecord } from './types.js';
5
-
6
- export function toPascalCase(text: string, customWords?: StringRecord): string {
7
- const words = String(text).match(/[A-Z][a-z']+|\d+|[a-z']+/g);
8
-
9
- if (words === null) {
10
- return '';
11
- }
12
-
13
- let fixedWords = words.map(word => capitalize(word.replace(/'/g, '')));
14
-
15
- if (customWords && getType(customWords) === 'Object') {
16
- const replacements = new Map(
17
- Object.entries(customWords).map<KeyValueTuple<string, string>>(([key, value]) => [key.toLowerCase(), value]),
18
- );
19
-
20
- if (replacements.size) {
21
- // This takes a single word and returns the first matching replacement, if any.
22
- const replaceCustomWords = (word: string): string => replacements.get(word.toLowerCase()) ?? word;
23
-
24
- fixedWords = fixedWords.map(replaceCustomWords);
25
- }
26
- }
27
-
28
- return fixedWords.join('');
29
- }
package/src/trimEnd.ts DELETED
@@ -1,5 +0,0 @@
1
- import escapeRegExp from 'lodash.escaperegexp';
2
-
3
- export function trimEnd(str: string, char?: string): string {
4
- return char ? str.replace(new RegExp(`${escapeRegExp(char)}+$`), '') : str.trimEnd();
5
- }
@@ -1,18 +0,0 @@
1
- const isWhitespaceOnly = (input: string): boolean => /^\s*$/.test(input);
2
-
3
- export function trimIndentation(input: string): string {
4
- const lines = input.split('\n');
5
- const firstNonWhitespaceLine = lines.find(line => !isWhitespaceOnly(line));
6
- const whiteSpace = firstNonWhitespaceLine?.match(/^(?<whiteSpace>\s*)/)?.groups?.whiteSpace;
7
-
8
- if (whiteSpace) {
9
- const wsPattern = new RegExp(`^${whiteSpace}`);
10
-
11
- return lines
12
- .map(line => line.replace(wsPattern, ''))
13
- .join('\n')
14
- .trim();
15
- }
16
-
17
- return input;
18
- }
package/src/trimStart.ts DELETED
@@ -1,5 +0,0 @@
1
- import escapeRegExp from 'lodash.escaperegexp';
2
-
3
- export function trimStart(str: string, char?: string): string {
4
- return char ? str.replace(new RegExp(`^${escapeRegExp(char)}+`), '') : str.trimStart();
5
- }
@@ -1,20 +0,0 @@
1
- import { isNumericValueArray } from './type-predicate.js';
2
- import type { NumericValue } from './types.js';
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
- }
@@ -1,48 +0,0 @@
1
- import type { NumericString, NumericValue, Primitive, UnknownRecord } from './types.js';
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';
37
-
38
- export const isPrimitive = (input: unknown): input is Primitive =>
39
- typeof input === 'string' ||
40
- typeof input === 'number' ||
41
- typeof input === 'bigint' ||
42
- typeof input === 'boolean' ||
43
- typeof input === 'undefined' ||
44
- typeof input === 'symbol' ||
45
- input === null;
46
-
47
- export const isObject = <T extends UnknownRecord = UnknownRecord>(input: unknown): input is T =>
48
- input !== null && typeof input === 'object' && !Array.isArray(input);
package/src/types.ts DELETED
@@ -1,42 +0,0 @@
1
- export type Primitive = string | number | boolean | bigint | symbol | undefined | null;
2
-
3
- // eslint-disable-next-line @typescript-eslint/ban-types
4
- export type Builtin = Date | Error | Function | Primitive | RegExp;
5
-
6
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
- export type AnyRecord = Record<PropertyKey, any>;
8
-
9
- export type StringRecord = Record<string, string>;
10
-
11
- export type UnknownRecord = Record<PropertyKey, unknown>;
12
-
13
- export type NumericString<T extends string | number = number> = `${T}` extends `${number}` ? `${T}` : never;
14
-
15
- export type NumericValue = number | bigint | NumericString;
16
-
17
- export type MaybePlural<T extends string> = T | `${T}s`;
18
-
19
- export type StringKeys<T> = keyof T & string;
20
-
21
- export type IfDefined<T, D, U> = undefined extends T ? U : D;
22
-
23
- export type IfNever<T, N, O> = [T] extends [never] ? N : O;
24
-
25
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
26
- export type ReturnTypeDefault<F, D = undefined> = F extends (...args: any) => infer R ? R : D;
27
-
28
- export type AnyNewable = {
29
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
- new (...args: any[]): any;
31
- };
32
-
33
- export type JoinTuples<A extends unknown[], B extends unknown[]> = [...A, ...B];
34
-
35
- export type RangeTuple<T> = [min: T, max: T];
36
-
37
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
- export type RangeTupleDistributive<T> = T extends any ? [min: T, max: T] : never;
39
-
40
- export type NumberRangeTuple = RangeTuple<number>;
41
-
42
- export type KeyValueTuple<K extends PropertyKey = PropertyKey, V = unknown> = [key: K, value: V];
@@ -1,3 +0,0 @@
1
- export function uniqueItems<T>(data: T[]): T[] {
2
- return [...new Set<T>(data)];
3
- }
package/src/until.ts DELETED
@@ -1,130 +0,0 @@
1
- import type { AnyRecord } from './types.js';
2
- import { getType } from './getType.js';
3
-
4
- export interface UntilContext {
5
- callCount: number;
6
- lastCall: number | undefined;
7
- data: AnyRecord;
8
- options: UntilOptions;
9
- }
10
-
11
- export type DelayFn = (context: Readonly<UntilContext>) => number;
12
-
13
- export type Delay = DelayFn | number;
14
-
15
- export type UntilOptions = {
16
- delay: Delay;
17
- timeout?: Delay;
18
- callLimit?: number;
19
- };
20
-
21
- export type ResolverValue<T> = T | PromiseLike<T>;
22
-
23
- export type ResolveFn<T> = (value: ResolverValue<T>) => void;
24
-
25
- export type RejectFn = (error?: Error) => void;
26
-
27
- export type UntilCallback<T> = (resolve: ResolveFn<T>, reject: RejectFn, context: Readonly<UntilContext>) => void;
28
-
29
- const defaultOptions: Readonly<UntilOptions> = {
30
- delay: 10,
31
- };
32
-
33
- export const isDelay = (input: unknown): input is Delay => Number.isInteger(input) || typeof input === 'function';
34
-
35
- /**
36
- * Return a Promise that delegates resolving/rejecting to the passed in function.
37
- */
38
- export function until<T>(fn: UntilCallback<T>, options: UntilOptions = defaultOptions): Promise<T> {
39
- if (typeof fn !== 'function') {
40
- return Promise.reject(new Error('fn must be a function'));
41
- }
42
-
43
- if (!options || typeof options !== 'object') {
44
- return Promise.reject(new TypeError(`options must be an object. ${getType(options)} provided.`));
45
- }
46
-
47
- const { delay, timeout, callLimit } = Object.assign({}, defaultOptions, options);
48
-
49
- const getDelay = (delay: Delay, context: UntilContext): number =>
50
- typeof delay === 'function' ? delay(context) : delay;
51
-
52
- if (!isDelay(delay)) {
53
- return Promise.reject(new TypeError('invalid delay value'));
54
- }
55
-
56
- if (timeout !== undefined && !isDelay(timeout)) {
57
- return Promise.reject(new TypeError('invalid timeout value'));
58
- }
59
-
60
- if (callLimit !== undefined && !Number.isInteger(callLimit)) {
61
- return Promise.reject(new TypeError('invalid callLimit value'));
62
- }
63
-
64
- return new Promise<T>((resolutionFn: ResolveFn<T>, rejectionFn: RejectFn) => {
65
- let callCount = 0;
66
- let lastCall: number | undefined;
67
- let done = false;
68
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
- let timer: any;
70
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
71
- let timeoutTimer: any;
72
-
73
- const finish = (): void => {
74
- done = true;
75
- clearTimeout(timer);
76
- clearTimeout(timeoutTimer);
77
- };
78
-
79
- const resolve: ResolveFn<T> = (value: ResolverValue<T>): void => {
80
- resolutionFn(value);
81
- finish();
82
- };
83
-
84
- const reject: RejectFn = (error?: Error): void => {
85
- rejectionFn(error);
86
- finish();
87
- };
88
-
89
- const context: Readonly<UntilContext> = Object.freeze({
90
- get callCount() {
91
- return callCount;
92
- },
93
- get lastCall() {
94
- return lastCall;
95
- },
96
- get options() {
97
- return options;
98
- },
99
- data: {},
100
- });
101
-
102
- const callUntilDone = (fn: UntilCallback<T>, delay: Delay, resolve: ResolveFn<T>, reject: RejectFn): void => {
103
- try {
104
- if (callLimit && callCount >= callLimit) {
105
- throw new Error(`until callLimit reached: ${callLimit}`);
106
- }
107
-
108
- ++callCount;
109
-
110
- fn(resolve, reject, context);
111
-
112
- lastCall = Date.now();
113
-
114
- if (!done) {
115
- timer = setTimeout(callUntilDone, getDelay(delay, context), fn, delay, resolve, reject);
116
- }
117
- } catch (error) {
118
- reject(error instanceof Error ? error : new Error(`${error}`));
119
- }
120
- };
121
-
122
- callUntilDone(fn, delay, resolve, reject);
123
-
124
- if (!done && timeout !== undefined) {
125
- timeoutTimer = setTimeout(() => {
126
- reject(new Error('until: timed out'));
127
- }, getDelay(timeout, context));
128
- }
129
- });
130
- }