@mmb-digital/shared-libs-auto 0.0.21 → 0.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/dist/formatters/formatBankAccount/utils/innerFormatBankAccount.js +1 -1
- package/dist/formatters/formatBytes/formatBytes.js +3 -6
- package/dist/formatters/formatBytes/formatBytes.test.js +7 -0
- package/dist/formatters/formatNumber/formatNumber.test.js +4 -0
- package/dist/formatters/formatNumber/utils/innerFormatNumber.js +16 -2
- package/dist/utils/arrayBufferToBase64/arrayBufferToBase64.js +1 -1
- package/dist/utils/base64ToArrayBuffer/base64ToArrayBuffer.js +1 -1
- package/dist/utils/chunkArray/chunkArray.js +6 -4
- package/dist/utils/chunkArray/chunkArray.test.js +5 -0
- package/dist/utils/cleanObject/cleanObject.d.ts +3 -2
- package/dist/utils/cleanObject/cleanObject.js +3 -16
- package/dist/utils/cleanObject/cleanObject.test.js +47 -9
- package/dist/utils/cleanObject/types.d.ts +6 -0
- package/dist/utils/cleanObject/types.js +1 -0
- package/dist/utils/cleanObject/utils/innerCleanObject.d.ts +6 -0
- package/dist/utils/cleanObject/utils/innerCleanObject.js +37 -0
- package/dist/utils/constants.d.ts +1 -0
- package/dist/utils/constants.js +1 -0
- package/dist/utils/getDateObject/getDateObject.d.ts +8 -1
- package/dist/utils/getDateObject/getDateObject.js +10 -2
- package/dist/utils/getDateObject/getDateObject.test.js +24 -3
- package/dist/utils/getDateObject/utils/parseDate.d.ts +6 -0
- package/dist/utils/getDateObject/utils/parseDate.js +21 -0
- package/dist/utils/getLastSpecificDate/getLastSpecificDate.d.ts +22 -0
- package/dist/utils/getLastSpecificDate/getLastSpecificDate.js +42 -0
- package/dist/utils/getLastSpecificDate/getLastSpecificDate.test.d.ts +1 -0
- package/dist/utils/getLastSpecificDate/getLastSpecificDate.test.js +108 -0
- package/dist/utils/getLastSpecificDate/utils/getSpecificDate.d.ts +4 -0
- package/dist/utils/getLastSpecificDate/utils/getSpecificDate.js +9 -0
- package/dist/utils/getNumber/getNumber.test.js +26 -26
- package/dist/utils/getNumberFloat/getNumberFloat.js +1 -1
- package/dist/utils/getNumberFloat/getNumberFloat.test.js +17 -17
- package/dist/utils/getObjectDiff/getObjectDiff.js +1 -1
- package/dist/utils/getObjectDiff/getObjectDiff.test.js +9 -0
- package/dist/utils/getObjectValue/getObjectValue.js +2 -1
- package/dist/utils/getObjectValue/getObjectValue.test.js +11 -8
- package/dist/utils/getQuarterFromDate/getQuarterFromDate.d.ts +4 -0
- package/dist/utils/getQuarterFromDate/getQuarterFromDate.js +26 -0
- package/dist/utils/getQuarterFromDate/getQuarterFromDate.test.d.ts +1 -0
- package/dist/utils/getQuarterFromDate/getQuarterFromDate.test.js +151 -0
- package/dist/utils/getWeekFromDate/getWeekFromDate.d.ts +4 -0
- package/dist/utils/getWeekFromDate/getWeekFromDate.js +28 -0
- package/dist/utils/getWeekFromDate/getWeekFromDate.test.d.ts +1 -0
- package/dist/utils/getWeekFromDate/getWeekFromDate.test.js +130 -0
- package/dist/utils/groupBy/groupBy.js +10 -3
- package/dist/utils/groupBy/groupBy.test.js +6 -0
- package/dist/utils/hasObjectProperty/hasObjectProperty.js +5 -4
- package/dist/utils/hasObjectProperty/hasObjectProperty.test.js +5 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/mapObjectKeys/mapObjectKeys.js +6 -1
- package/dist/utils/mapObjectKeys/mapObjectKeys.test.js +7 -0
- package/dist/utils/mergeDeep/mergeDeep.js +2 -23
- package/dist/utils/mergeDeep/mergeDeep.test.js +5 -0
- package/dist/utils/mergeDeep/utils/innerMergeDeep.d.ts +5 -0
- package/dist/utils/mergeDeep/utils/innerMergeDeep.js +31 -0
- package/dist/utils/range/createRange.js +2 -0
- package/dist/utils/range/createRange.test.js +9 -5
- package/dist/utils/range/isInRange.js +2 -0
- package/dist/utils/range/isInRange.test.js +5 -0
- package/dist/utils/range/unionRange.test.js +2 -2
- package/dist/utils/removeSpecialChars/removeSpecialChars.test.js +9 -0
- package/dist/utils/removeWhitespacesFromUnknown/removeWhitespacesFromUnknown.test.js +2 -2
- package/dist/utils/setObjectValue/setObjectValue.js +1 -1
- package/dist/validators/index.d.ts +3 -0
- package/dist/validators/index.js +3 -0
- package/dist/validators/isBankAccount/isBankAccount.d.ts +3 -1
- package/dist/validators/isBankAccount/isBankAccount.js +11 -21
- package/dist/validators/isBankAccount/isBankAccount.test.js +6 -3
- package/dist/validators/isEmail/isEmail.js +5 -1
- package/dist/validators/isEmail/isEmail.test.js +15 -0
- package/dist/validators/isEqual/isEqual.d.ts +1 -1
- package/dist/validators/isEqual/isEqual.js +7 -3
- package/dist/validators/isEqual/isEqual.test.js +12 -0
- package/dist/validators/isModulo11/isModulo11.js +2 -0
- package/dist/validators/isModulo11/isModulo11.test.js +3 -0
- package/dist/validators/isPlainObject/isPlainObject.d.ts +4 -0
- package/dist/validators/isPlainObject/isPlainObject.js +9 -0
- package/dist/validators/isPlainObject/isPlainObject.test.d.ts +1 -0
- package/dist/validators/isPlainObject/isPlainObject.test.js +24 -0
- package/dist/validators/isValidDate/isValidDate.d.ts +1 -0
- package/dist/validators/isValidDate/isValidDate.js +4 -26
- package/dist/validators/isValidDate/isValidDate.test.js +12 -1
- package/dist/validators/isValidDateInstance/isValidDateInstance.d.ts +4 -0
- package/dist/validators/isValidDateInstance/isValidDateInstance.js +11 -0
- package/dist/validators/isValidDateInstance/isValidDateInstance.test.d.ts +1 -0
- package/dist/validators/isValidDateInstance/isValidDateInstance.test.js +67 -0
- package/dist/validators/isValidForeignPhoneNumber/isValidForeignPhoneNumber.d.ts +1 -1
- package/dist/validators/isValidForeignPhoneNumber/isValidForeignPhoneNumber.js +2 -2
- package/dist/validators/isValidMrzCheckDigit/isValidMrzCheckDigit.d.ts +6 -0
- package/dist/validators/isValidMrzCheckDigit/isValidMrzCheckDigit.js +27 -0
- package/dist/validators/isValidMrzCheckDigit/isValidMrzCheckDigit.test.d.ts +1 -0
- package/dist/validators/isValidMrzCheckDigit/isValidMrzCheckDigit.test.js +26 -0
- package/dist/yup/index.d.ts +1 -0
- package/dist/yup/index.js +1 -0
- package/dist/yup/isDateAtLeastYearsAgo/isDateAtLeastYearsAgoYupTest.d.ts +12 -0
- package/dist/yup/isDateAtLeastYearsAgo/isDateAtLeastYearsAgoYupTest.js +32 -0
- package/dist/yup/isDateAtLeastYearsAgo/isDateAtLeastYearsAgoYupTest.test.d.ts +1 -0
- package/dist/yup/isDateAtLeastYearsAgo/isDateAtLeastYearsAgoYupTest.test.js +64 -0
- package/dist/yup/isDateSameOrAfter/isDateSameOrAfterYupTest.js +12 -4
- package/dist/yup/isDateSameOrBefore/isDateSameOrBeforeYupTest.js +12 -4
- package/dist/yup/maxDigitsLength/maxDigitsLengthYupTest.js +2 -0
- package/dist/yup/maxDigitsLength/maxDigitsLengthYupTest.test.js +6 -0
- package/dist/yup/minDigitsLength/minDigitsLengthYupTest.js +2 -0
- package/dist/yup/minDigitsLength/minDigitsLengthYupTest.test.js +6 -0
- package/package.json +23 -22
package/README.md
CHANGED
|
@@ -27,7 +27,7 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
27
27
|
|
|
28
28
|
## Features
|
|
29
29
|
|
|
30
|
-
###
|
|
30
|
+
### Formatters
|
|
31
31
|
|
|
32
32
|
#### Bank Account
|
|
33
33
|
- **`formatBankAccount(value: BankAccountInput, fallback?: string): string`** - Formats bank account number to standard format (prefix-account/bankCode).
|
|
@@ -53,7 +53,7 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
53
53
|
- **`inputFormatICO(value: string | number | null | undefined): string | null`** - Formats ICO input in real-time while typing.
|
|
54
54
|
|
|
55
55
|
#### Numbers
|
|
56
|
-
- **`formatNumber(value: number | string | null | undefined, decimals?: number, fallback?: string): string`** - Formats number with options for separators
|
|
56
|
+
- **`formatNumber(value: number | string | null | undefined, decimals?: number, fallback?: string): string`** - Formats number with options for separators and decimal places.
|
|
57
57
|
- **`formatPercent(value: number | string | null | undefined, isDecimalValue?: boolean, decimals?: number, fallback?: string): string`** - Formats number as percentage.
|
|
58
58
|
- **`inputFormatNumber(value: number | string | null | undefined): string | null`** - Formats number input in real-time while typing.
|
|
59
59
|
- **`inputFormatFloat(value: number | string | null | undefined): string | null`** - Formats decimal number input in real-time while typing.
|
|
@@ -78,11 +78,13 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
78
78
|
|
|
79
79
|
### Types
|
|
80
80
|
- **`Prettify<T>`** - Prettify type
|
|
81
|
+
- **`Gender`** - Union of the exported birth-number gender values.
|
|
82
|
+
- **`Range`** - Object type with numeric `min` and `max` properties.
|
|
81
83
|
|
|
82
84
|
### Utils
|
|
83
85
|
|
|
84
86
|
#### Array Operations
|
|
85
|
-
- **`chunkArray<T>(input: unknown, size: number): T[]`** - Splits an array into chunks of specified size.
|
|
87
|
+
- **`chunkArray<T>(input: unknown, size: number): T[][]`** - Splits an array into chunks of specified size.
|
|
86
88
|
- **`groupBy<T, K extends string | number | symbol>(arr: T[], getKey: (item: T) => K): Record<K, T[] | undefined>`** - Groups array elements by a specified key.
|
|
87
89
|
- **`joinBy(separator: string, stringArray: Array<string | undefined>): string`** - Joins array elements by a key with a separator.
|
|
88
90
|
- **`xor<T extends unknown[], R extends unknown[]>(a: T, b: R): Array<T[number] | R[number]>`** - Returns symmetric difference between two arrays (elements that exist in only one array).
|
|
@@ -93,6 +95,11 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
93
95
|
- **`getDateFromBirthNumber(value: string | undefined | null): Date | null`** - Extracts date of birth from a birth number.
|
|
94
96
|
- **`getGenderFromBirthNumber(value: string | undefined | null): Gender`** - Determines gender from a birth number ('male' | 'female').
|
|
95
97
|
|
|
98
|
+
#### Date Operations
|
|
99
|
+
- **`getQuarterFromDate(input: unknown): number | null`** - Returns the quarter (1–4) for a valid date input, or `null` for an invalid input.
|
|
100
|
+
- **`getWeekFromDate(input: unknown): number | null`** - Returns the week number (1–53) for a valid date input, or `null` for an invalid input.
|
|
101
|
+
- **`getLastSpecificDate(input: unknown, dayOfWeek?: number): Date | null`** - Returns the last specific date of the week, or `null` for an invalid input. The default day is Monday.
|
|
102
|
+
|
|
96
103
|
#### File Operations
|
|
97
104
|
- **`arrayBufferToBase64(buffer: ArrayBuffer | Uint8Array): string`** - Converts ArrayBuffer to Base64 string.
|
|
98
105
|
- **`base64ToArrayBuffer(base64: string): Uint8Array<ArrayBuffer>`** - Converts Base64 string to ArrayBuffer.
|
|
@@ -108,7 +115,7 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
108
115
|
- **`getSafeMin(a: number | null | undefined, b: number | null | undefined): number | undefined`** - Returns min of two numbers with `null`/`undefined` fallback handling.
|
|
109
116
|
|
|
110
117
|
#### Object Operations
|
|
111
|
-
- **`cleanObject<T extends Record<string, unknown>>(obj: T | undefined | null):
|
|
118
|
+
- **`cleanObject<T extends Record<string, unknown>>(obj: T | undefined | null): CleanedObject<T>`** - Deeply removes undefined, null, empty string values, empty array and empty objects from an object.
|
|
112
119
|
- **`getObjectDiff<T extends Record<string, unknown>, R extends Record<string, unknown>>(object: T | undefined | null, base: R | undefined | null): Partial<T>`** - Returns differences between two objects.
|
|
113
120
|
- **`getObjectValue(obj: Record<string, unknown> | null | undefined, path: string | string[], defaultValue?: unknown): unknown`** - Gets nested object value by path string (e.g., 'user.address.city').
|
|
114
121
|
- **`setObjectValue<T extends Record<string, unknown>>(obj: T, path: string, value: unknown): T`** - Sets nested object value by path string.
|
|
@@ -134,8 +141,8 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
134
141
|
- **`makeAbsolutePath(...relativePaths: string[]): string`** - Converts relative path to absolute URL.
|
|
135
142
|
|
|
136
143
|
#### Browser Operations
|
|
137
|
-
- **`scrollToBottom(): void`** -
|
|
138
|
-
- **`scrollToTop(): void`** -
|
|
144
|
+
- **`scrollToBottom(): void`** - Smoothly scrolls the page to the bottom.
|
|
145
|
+
- **`scrollToTop(): void`** - Smoothly scrolls the page to the top.
|
|
139
146
|
- **`getDateObject(input: string): Date | null`** - Validates a date string and returns a `Date` instance, or `null` for invalid input.
|
|
140
147
|
|
|
141
148
|
### Validators
|
|
@@ -144,21 +151,23 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
144
151
|
- **`isArrayBuffer(value: unknown): value is ArrayBuffer`** - Checks if a value is an ArrayBuffer.
|
|
145
152
|
- **`isBlob(value: unknown): value is Blob`** - Checks if a value is a Blob.
|
|
146
153
|
- **`isBoolean(value: unknown): value is boolean`** - Checks if a value is a boolean.
|
|
147
|
-
- **`isFile(value: unknown):
|
|
154
|
+
- **`isFile(value: unknown): value is File`** - Checks if value is an instance of File.
|
|
148
155
|
- **`isFunction(value: unknown): value is Function`** - Checks if a value is a function.
|
|
149
156
|
- **`isNull(value: unknown): value is null`** - Checks if a value is null.
|
|
150
157
|
- **`isNullOrUndefined(value: unknown): value is null | undefined`** - Checks if a value is null or undefined.
|
|
151
158
|
- **`isNumber(value: unknown): value is number`** - Checks if a value is a number.
|
|
152
159
|
- **`isNumberOrString(value: unknown): value is number | string`** - Checks if a value is a number or string.
|
|
153
160
|
- **`isObject<T extends Record<string, unknown>>(value: unknown): value is T`** - Checks if a value is an object (excluding null and arrays).
|
|
161
|
+
- **`isPlainObject(value: unknown): value is Record<string, unknown>`** - Checks if a value is a plain object with an Object or null prototype.
|
|
154
162
|
- **`isString(value: unknown): value is string`** - Checks if a value is a string.
|
|
155
163
|
- **`isUndefined(value: unknown): value is undefined`** - Checks if a value is undefined.
|
|
156
164
|
|
|
157
165
|
#### Value Validators
|
|
158
166
|
- **`isEmpty<T>(value: T | undefined | null): value is undefined | null`** - Checks if a value is empty (null, undefined, empty string, empty array, or empty object).
|
|
159
167
|
- **`isEmptyString(value: unknown): value is ''`** - Checks whether a value is exactly an empty string (`''`).
|
|
160
|
-
- **`isEqual(a: unknown, b: unknown): boolean`** -
|
|
168
|
+
- **`isEqual(a: unknown, b: unknown): boolean`** - Compares primitives, arrays, plain objects, and Date instances by value; other object instances are compared by reference.
|
|
161
169
|
- **`isValidDate(input: string | null | undefined): boolean`** - Checks whether a date string is parseable into a valid `Date`.
|
|
170
|
+
- **`isValidDateInstance(input: unknown): input is Date`** - Checks if the provided input is a valid Date instance.
|
|
162
171
|
|
|
163
172
|
#### String Format Validators
|
|
164
173
|
- **`isEmail(value: string | undefined | null): boolean`** - Validates if a string is a valid email address.
|
|
@@ -182,20 +191,22 @@ import { isEmail, removeWhitespaces, useToggle } from '@mmb-digital/shared-libs-
|
|
|
182
191
|
- **`isValidIdentityCard(value: string | number | null | undefined): boolean`** - Validates Czech identity card number format.
|
|
183
192
|
- **`isValidPassport(value: string | null | undefined): boolean`** - Validates Czech passport number format.
|
|
184
193
|
- **`isValidVehicleIdentification(value: string | null | undefined): boolean`** - Validates vehicle identification number (VIN) format.
|
|
194
|
+
- **`isValidMrzCheckDigit(value: string | number | null | undefined, checkDigit: string | number | null | undefined): boolean`** - Validates MRZ check digit.
|
|
185
195
|
|
|
186
196
|
#### Yup Validators
|
|
187
197
|
- **`isBirthNumberYupTest(message: string)`** - Creates Yup `test` config for Czech birth number validation.
|
|
188
|
-
- **`isDateSameOrAfterYupWhen(message: string)`** - Creates Yup `when` condition for reference date being same or after a date.
|
|
189
|
-
- **`isDateSameOrBeforeYupWhen(message: string)`** - Creates Yup `when` condition for reference date being same or before a date.
|
|
198
|
+
- **`isDateSameOrAfterYupWhen(message: string)(maxDate: unknown[], schema: StringSchema)`** - Creates Yup `when` condition for reference date being same or after a date.
|
|
199
|
+
- **`isDateSameOrBeforeYupWhen(message: string)(minDate: unknown[], schema: StringSchema)`** - Creates Yup `when` condition for reference date being same or before a date.
|
|
190
200
|
- **`isDateYupTest(message: string)`** - Creates Yup `test` config for valid date validation.
|
|
191
201
|
- **`isDICYupTest(message: string)`** - Creates Yup `test` config for DIČ validation.
|
|
192
202
|
- **`isEmailYupTest(message: string)`** - Creates Yup `test` config for email validation.
|
|
193
203
|
- **`isModulo11YupTest(message: string)`** - Creates Yup `test` config for modulo 11 validation.
|
|
194
204
|
- **`isICOYupTest(message: string)`** - Creates Yup `test` config for IČO validation.
|
|
195
|
-
- **`isNumberSameOrGreaterYupWhen(message: string)`** - Creates Yup `when` condition for number being same or greater than reference.
|
|
196
|
-
- **`isNumberSameOrLowerYupWhen(message: string)`** - Creates Yup `when` condition for number being same or lower than reference.
|
|
197
|
-
- **`
|
|
198
|
-
- **`
|
|
205
|
+
- **`isNumberSameOrGreaterYupWhen(message: string)(max: unknown[], schema: NumberSchema)`** - Creates Yup `when` condition for number being same or greater than reference.
|
|
206
|
+
- **`isNumberSameOrLowerYupWhen(message: string)(min: unknown[], schema: NumberSchema)`** - Creates Yup `when` condition for number being same or lower than reference.
|
|
207
|
+
- **`isDateAtLeastYearsAgoYupTest(minimumYears: number, message: string)`** - Creates Yup `test` config for minimum year validation.
|
|
208
|
+
- **`maxDigitsLengthYupTest(max: number, message: (params: { max: number }) => string)`** - Creates Yup `test` config for maximum digits length.
|
|
209
|
+
- **`minDigitsLengthYupTest(min: number, message: (params: { min: number }) => string)`** - Creates Yup `test` config for minimum digits length.
|
|
199
210
|
|
|
200
211
|
|
|
201
212
|
## License
|
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
export const innerFormatBankAccount = (value) => {
|
|
5
5
|
const { prefix, number, bankCode } = value;
|
|
6
6
|
const accountNumber = [number.trim(), bankCode.trim()].join('/');
|
|
7
|
-
return [prefix, accountNumber].filter(Boolean).join('-');
|
|
7
|
+
return [prefix, accountNumber].filter(Boolean).join('-').trim();
|
|
8
8
|
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isNullOrUndefined } from '../../validators/isNullOrUndefined/isNullOrUndefined.js';
|
|
2
2
|
import { EMPTY_VALUE_PLACEHOLDER } from '../const.js';
|
|
3
|
+
const MAX_DECIMALS = 100;
|
|
3
4
|
/**
|
|
4
5
|
* Formats a number of bytes into a human-readable string.
|
|
5
6
|
* @example "1.5 MB"
|
|
@@ -7,16 +8,12 @@ import { EMPTY_VALUE_PLACEHOLDER } from '../const.js';
|
|
|
7
8
|
export const formatBytes = (bytes, decimals = 2, fallback = EMPTY_VALUE_PLACEHOLDER) => {
|
|
8
9
|
if (isNullOrUndefined(bytes))
|
|
9
10
|
return fallback;
|
|
10
|
-
if (bytes < 0)
|
|
11
|
-
return fallback;
|
|
12
|
-
if (bytes === Number.POSITIVE_INFINITY)
|
|
11
|
+
if (!Number.isFinite(bytes) || bytes < 0)
|
|
13
12
|
return fallback;
|
|
14
13
|
if (bytes === 0)
|
|
15
14
|
return '0 Bytes';
|
|
16
|
-
if (decimals < 0)
|
|
17
|
-
decimals = 0;
|
|
18
15
|
const k = 1024;
|
|
19
|
-
const dm = Math.max(0, decimals);
|
|
16
|
+
const dm = Number.isFinite(decimals) ? Math.min(MAX_DECIMALS, Math.max(0, decimals)) : 0;
|
|
20
17
|
const sizes = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
|
21
18
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
22
19
|
return `${Number.parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
|
|
@@ -21,6 +21,10 @@ describe('formatBytes', () => {
|
|
|
21
21
|
it('should handle negative decimals as 0', () => {
|
|
22
22
|
expect(formatBytes(1536, -1)).toBe('2 kB');
|
|
23
23
|
});
|
|
24
|
+
it('should normalize invalid decimal counts', () => {
|
|
25
|
+
expect(formatBytes(1536, 101)).toBe(formatBytes(1536, 100));
|
|
26
|
+
expect(formatBytes(1536, Number.POSITIVE_INFINITY)).toBe('2 kB');
|
|
27
|
+
});
|
|
24
28
|
it('should format large numbers', () => {
|
|
25
29
|
expect(formatBytes(1024 ** 4)).toBe('1 TB');
|
|
26
30
|
});
|
|
@@ -34,6 +38,9 @@ describe('formatBytes', () => {
|
|
|
34
38
|
it('should return fallback for positive infinity', () => {
|
|
35
39
|
expect(formatBytes(Number.POSITIVE_INFINITY)).toBe(EMPTY_VALUE_PLACEHOLDER);
|
|
36
40
|
});
|
|
41
|
+
it('should return fallback for NaN', () => {
|
|
42
|
+
expect(formatBytes(Number.NaN)).toBe(EMPTY_VALUE_PLACEHOLDER);
|
|
43
|
+
});
|
|
37
44
|
it('should return fallback for negative infinity', () => {
|
|
38
45
|
expect(formatBytes(Number.NEGATIVE_INFINITY)).toBe(EMPTY_VALUE_PLACEHOLDER);
|
|
39
46
|
});
|
|
@@ -18,6 +18,10 @@ describe('formatNumber', () => {
|
|
|
18
18
|
expect(formatNumber(1234.56, 2)).toBe('1 234,56');
|
|
19
19
|
expect(formatNumber('5678.99', 1)).toBe('5 679,0');
|
|
20
20
|
});
|
|
21
|
+
it('normalizes invalid decimal counts', () => {
|
|
22
|
+
expect(formatNumber(1.5, 101)).toBe(formatNumber(1.5, 100));
|
|
23
|
+
expect(formatNumber(1234.56, Number.POSITIVE_INFINITY)).toBe('1 235');
|
|
24
|
+
});
|
|
21
25
|
it('formats negative numbers', () => {
|
|
22
26
|
expect(formatNumber(-1234.56, 2)).toBe('-1 234,56');
|
|
23
27
|
expect(formatNumber('-5678.99', 1)).toBe('-5 679,0');
|
|
@@ -1,6 +1,20 @@
|
|
|
1
|
-
const
|
|
1
|
+
const MAX_DECIMALS = 100;
|
|
2
|
+
/**
|
|
3
|
+
* Formats the integer part of a number with space as thousand separator.
|
|
4
|
+
*/
|
|
5
|
+
const formatIntegerPart = (integerPart) => {
|
|
6
|
+
const sign = integerPart.startsWith('-') ? '-' : '';
|
|
7
|
+
const digits = sign ? integerPart.slice(1) : integerPart;
|
|
8
|
+
const reversedDigits = digits.split('').reverse().join('');
|
|
9
|
+
const formattedDigits = reversedDigits.replace(/(\d{3})/g, '$1 ').trimEnd();
|
|
10
|
+
return `${sign}${formattedDigits.split('').reverse().join('')}`;
|
|
11
|
+
};
|
|
2
12
|
/**
|
|
3
13
|
* Internal utility to format a number with specified decimal places,
|
|
4
14
|
* using comma as decimal separator and space as thousand separator.
|
|
5
15
|
*/
|
|
6
|
-
export const innerFormatNumber = (valueNumber, decimals) => valueNumber
|
|
16
|
+
export const innerFormatNumber = (valueNumber, decimals) => valueNumber
|
|
17
|
+
.toFixed(Number.isFinite(decimals) ? Math.min(MAX_DECIMALS, Math.max(0, decimals)) : 0)
|
|
18
|
+
.split('.')
|
|
19
|
+
.map((part, index) => (index === 0 ? formatIntegerPart(part) : part))
|
|
20
|
+
.join(',');
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Converts a base64 string to an ArrayBuffer.
|
|
3
3
|
*/
|
|
4
4
|
export const base64ToArrayBuffer = (base64) => {
|
|
5
|
-
const binaryString = globalThis.
|
|
5
|
+
const binaryString = globalThis.atob(base64);
|
|
6
6
|
const binaryLen = binaryString.length;
|
|
7
7
|
const bytes = new Uint8Array(binaryLen);
|
|
8
8
|
return bytes.map((byte, index) => binaryString.charCodeAt(index));
|
|
@@ -5,9 +5,11 @@
|
|
|
5
5
|
export const chunkArray = (input, size) => {
|
|
6
6
|
if (!Array.isArray(input))
|
|
7
7
|
return [];
|
|
8
|
-
if (size <= 0)
|
|
8
|
+
if (!Number.isInteger(size) || size <= 0)
|
|
9
9
|
return [];
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
const chunks = [];
|
|
11
|
+
for (let index = 0; index < input.length; index += size) {
|
|
12
|
+
chunks.push(input.slice(index, index + size));
|
|
13
|
+
}
|
|
14
|
+
return chunks;
|
|
13
15
|
};
|
|
@@ -30,4 +30,9 @@ describe('chunkArray', () => {
|
|
|
30
30
|
expect(chunkArray([1, 2, 3], 0)).toEqual([]);
|
|
31
31
|
expect(chunkArray([1, 2, 3], -1)).toEqual([]);
|
|
32
32
|
});
|
|
33
|
+
test('returns an empty array for non-integer or non-finite size', () => {
|
|
34
|
+
expect(chunkArray([1, 2, 3], 1.5)).toEqual([]);
|
|
35
|
+
expect(chunkArray([1, 2, 3], Number.NaN)).toEqual([]);
|
|
36
|
+
expect(chunkArray([1, 2, 3], Number.POSITIVE_INFINITY)).toEqual([]);
|
|
37
|
+
});
|
|
33
38
|
});
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import type { CleanedObject } from './types.js';
|
|
1
2
|
/**
|
|
2
|
-
* Deeply removes undefined, null,
|
|
3
|
+
* Deeply removes undefined, null, empty string values, empty array and empty objects from an object.
|
|
3
4
|
*/
|
|
4
|
-
export declare function cleanObject<T extends Record<string, unknown>>(obj: T | undefined | null):
|
|
5
|
+
export declare function cleanObject<T extends Record<string, unknown>>(obj: T | undefined | null): CleanedObject<T>;
|
|
@@ -1,20 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { isObject } from '../../validators/isObject/isObject.js';
|
|
3
|
-
import { isString } from '../../validators/isString/isString.js';
|
|
1
|
+
import { innerCleanObject } from './utils/innerCleanObject.js';
|
|
4
2
|
/**
|
|
5
|
-
* Deeply removes undefined, null,
|
|
3
|
+
* Deeply removes undefined, null, empty string values, empty array and empty objects from an object.
|
|
6
4
|
*/
|
|
7
5
|
export function cleanObject(obj) {
|
|
8
|
-
|
|
9
|
-
return {};
|
|
10
|
-
const cleanedObject = Object.entries(obj).reduce((result, [key, value]) => {
|
|
11
|
-
if (isNullOrUndefined(value) || (isString(value) && value.trim() === ''))
|
|
12
|
-
return result;
|
|
13
|
-
if (isObject(value)) {
|
|
14
|
-
const cleanedNestedObject = cleanObject(value);
|
|
15
|
-
return { ...result, [key]: cleanedNestedObject };
|
|
16
|
-
}
|
|
17
|
-
return { ...result, [key]: value };
|
|
18
|
-
}, {});
|
|
19
|
-
return cleanedObject;
|
|
6
|
+
return innerCleanObject(obj, new WeakSet());
|
|
20
7
|
}
|
|
@@ -16,9 +16,7 @@ describe('cleanObject', () => {
|
|
|
16
16
|
expect(cleanObject(obj)).toEqual({
|
|
17
17
|
e: 'valid',
|
|
18
18
|
f: 0,
|
|
19
|
-
g: false
|
|
20
|
-
h: [],
|
|
21
|
-
i: {}
|
|
19
|
+
g: false
|
|
22
20
|
});
|
|
23
21
|
});
|
|
24
22
|
test('preserves non-empty strings, numbers, booleans, objects, arrays', () => {
|
|
@@ -39,22 +37,62 @@ describe('cleanObject', () => {
|
|
|
39
37
|
const obj = { a: ' ', b: 'not empty ', c: 'valid' };
|
|
40
38
|
expect(cleanObject(obj)).toEqual({ b: 'not empty ', c: 'valid' });
|
|
41
39
|
});
|
|
42
|
-
test('does not remove zero
|
|
43
|
-
const obj = { a: 0, b: false
|
|
40
|
+
test('does not remove zero and false', () => {
|
|
41
|
+
const obj = { a: 0, b: false };
|
|
44
42
|
expect(cleanObject(obj)).toEqual(obj);
|
|
45
43
|
});
|
|
46
|
-
test('does clean nested objects', () => {
|
|
44
|
+
test('does clean nested objects and arrays', () => {
|
|
47
45
|
const obj = {
|
|
48
46
|
a: { x: null, y: '' },
|
|
49
|
-
b: [''],
|
|
47
|
+
b: ['', null, undefined, 'valid'],
|
|
50
48
|
c: 'valid',
|
|
51
49
|
d: null,
|
|
52
50
|
e: ''
|
|
53
51
|
};
|
|
54
52
|
expect(cleanObject(obj)).toEqual({
|
|
55
|
-
|
|
56
|
-
b: [''],
|
|
53
|
+
b: ['valid'],
|
|
57
54
|
c: 'valid'
|
|
58
55
|
});
|
|
59
56
|
});
|
|
57
|
+
test('does clean deeply nested objects and arrays', () => {
|
|
58
|
+
const obj = {
|
|
59
|
+
a: [0, 1, false, true, '', 'ok', null, undefined],
|
|
60
|
+
b: [{ x: null }, { y: 'valid' }, { z: '' }, { w: undefined }],
|
|
61
|
+
c: [{ x: [{ y: [{ z: null }] }] }]
|
|
62
|
+
};
|
|
63
|
+
expect(cleanObject(obj)).toEqual({
|
|
64
|
+
a: [0, 1, false, true, 'ok'],
|
|
65
|
+
b: [{ y: 'valid' }]
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
test('removes whitespace-only strings inside arrays', () => {
|
|
69
|
+
const obj = { a: [' ', 'valid', '\t', 'ok'] };
|
|
70
|
+
expect(cleanObject(obj)).toEqual({ a: ['valid', 'ok'] });
|
|
71
|
+
});
|
|
72
|
+
test('return empty object if all values are null, undefined, or empty strings', () => {
|
|
73
|
+
const obj = {
|
|
74
|
+
a: null,
|
|
75
|
+
b: undefined,
|
|
76
|
+
c: '',
|
|
77
|
+
d: ' ',
|
|
78
|
+
e: { f: null, g: '' },
|
|
79
|
+
h: [null, undefined, ''],
|
|
80
|
+
q: [{ x: null }, { y: '' }]
|
|
81
|
+
};
|
|
82
|
+
expect(cleanObject(obj)).toEqual({});
|
|
83
|
+
});
|
|
84
|
+
test('preserves non-plain object values', () => {
|
|
85
|
+
const date = new Date('2025-01-01');
|
|
86
|
+
const map = new Map([['key', 'value']]);
|
|
87
|
+
expect(cleanObject({ date, map, values: [date, map] })).toEqual({
|
|
88
|
+
date,
|
|
89
|
+
map,
|
|
90
|
+
values: [date, map]
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
test('does not stack overflow on circular references', () => {
|
|
94
|
+
const obj = { a: 'valid' };
|
|
95
|
+
obj.self = obj;
|
|
96
|
+
expect(() => cleanObject(obj)).not.toThrow();
|
|
97
|
+
});
|
|
60
98
|
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
type CleanedArrayItem<Item> = Item extends Record<string, unknown> ? CleanedObject<Item> : Exclude<Item, null | undefined | ''>;
|
|
2
|
+
type CleanedArray<A> = A extends Array<infer Item> ? Array<CleanedArrayItem<Item>> : never;
|
|
3
|
+
export type CleanedObject<T extends Record<string, unknown>> = {
|
|
4
|
+
[K in keyof T]?: NonNullable<T[K]> extends Array<unknown> ? CleanedArray<NonNullable<T[K]>> : NonNullable<T[K]> extends Record<string, unknown> ? CleanedObject<NonNullable<T[K]>> : Exclude<T[K], null | ''>;
|
|
5
|
+
};
|
|
6
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CleanedObject } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Internal utility that recursively removes undefined, null, empty string values, empty array
|
|
4
|
+
* and empty objects from an object, guarding against circular references via `seen`.
|
|
5
|
+
*/
|
|
6
|
+
export declare const innerCleanObject: <T extends Record<string, unknown>>(obj: T | undefined | null, seen: WeakSet<object>) => CleanedObject<T>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { isNullOrUndefined } from '../../../validators/isNullOrUndefined/isNullOrUndefined.js';
|
|
2
|
+
import { isPlainObject } from '../../../validators/isPlainObject/isPlainObject.js';
|
|
3
|
+
import { isString } from '../../../validators/isString/isString.js';
|
|
4
|
+
/**
|
|
5
|
+
* Internal utility that recursively removes undefined, null, empty string values, empty array
|
|
6
|
+
* and empty objects from an object, guarding against circular references via `seen`.
|
|
7
|
+
*/
|
|
8
|
+
export const innerCleanObject = (obj, seen) => {
|
|
9
|
+
if (isNullOrUndefined(obj) || !isPlainObject(obj))
|
|
10
|
+
return {};
|
|
11
|
+
if (seen.has(obj))
|
|
12
|
+
return {};
|
|
13
|
+
seen.add(obj);
|
|
14
|
+
const cleanedObject = Object.entries(obj).reduce((result, [key, value]) => {
|
|
15
|
+
if (isNullOrUndefined(value) || (isString(value) && value.trim() === ''))
|
|
16
|
+
return result;
|
|
17
|
+
if (isPlainObject(value)) {
|
|
18
|
+
const cleanedNestedObject = innerCleanObject(value, seen);
|
|
19
|
+
if (Object.keys(cleanedNestedObject).length === 0)
|
|
20
|
+
return result;
|
|
21
|
+
return { ...result, [key]: cleanedNestedObject };
|
|
22
|
+
}
|
|
23
|
+
if (Array.isArray(value)) {
|
|
24
|
+
const cleanedArray = value
|
|
25
|
+
.map(item => (isPlainObject(item) ? innerCleanObject(item, seen) : item))
|
|
26
|
+
.filter(item => !isNullOrUndefined(item) &&
|
|
27
|
+
!(isString(item) && item.trim() === '') &&
|
|
28
|
+
!(isPlainObject(item) && Object.keys(item).length === 0));
|
|
29
|
+
if (cleanedArray.length === 0)
|
|
30
|
+
return result;
|
|
31
|
+
return { ...result, [key]: cleanedArray };
|
|
32
|
+
}
|
|
33
|
+
return { ...result, [key]: value };
|
|
34
|
+
}, {});
|
|
35
|
+
seen.delete(obj);
|
|
36
|
+
return cleanedObject;
|
|
37
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const DANGEROUS_KEYS: Set<string>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Gets a Date object from a supported date string.
|
|
3
|
+
*
|
|
4
|
+
* Supported formats:
|
|
5
|
+
* - `2025-05-21 12:34:51` (YYYY-MM-DD HH:mm:ss)
|
|
6
|
+
* - `2025-05-21 12:34` (YYYY-MM-DD HH:mm)
|
|
7
|
+
* - `2025-09-03T13:32:21.582Z` (ISO 8601)
|
|
8
|
+
* - `2025-05-21` (YYYY-MM-DD)
|
|
9
|
+
* - `05/21/2025` (MM/DD/YYYY)
|
|
3
10
|
*/
|
|
4
11
|
export declare const getDateObject: (input: string) => Date | null;
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import { isValidDate } from '../../validators/isValidDate/isValidDate.js';
|
|
2
|
+
import { parseDate } from './utils/parseDate.js';
|
|
2
3
|
/**
|
|
3
|
-
*
|
|
4
|
+
* Gets a Date object from a supported date string.
|
|
5
|
+
*
|
|
6
|
+
* Supported formats:
|
|
7
|
+
* - `2025-05-21 12:34:51` (YYYY-MM-DD HH:mm:ss)
|
|
8
|
+
* - `2025-05-21 12:34` (YYYY-MM-DD HH:mm)
|
|
9
|
+
* - `2025-09-03T13:32:21.582Z` (ISO 8601)
|
|
10
|
+
* - `2025-05-21` (YYYY-MM-DD)
|
|
11
|
+
* - `05/21/2025` (MM/DD/YYYY)
|
|
4
12
|
*/
|
|
5
13
|
export const getDateObject = (input) => {
|
|
6
14
|
const isValid = isValidDate(input);
|
|
7
15
|
if (!isValid)
|
|
8
16
|
return null;
|
|
9
|
-
return
|
|
17
|
+
return parseDate(input);
|
|
10
18
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
2
|
import { getDateObject } from './getDateObject.js';
|
|
3
3
|
describe('Backend datetime format (2025-05-21 12:34:51)', () => {
|
|
4
4
|
it('Should return valid date', () => {
|
|
@@ -7,11 +7,32 @@ describe('Backend datetime format (2025-05-21 12:34:51)', () => {
|
|
|
7
7
|
expect(result?.toISOString()).toStrictEqual(new Date(2025, 4, 21, 12, 34, 51).toISOString());
|
|
8
8
|
});
|
|
9
9
|
});
|
|
10
|
+
describe('Backend datetime format without seconds (2025-05-21 12:34)', () => {
|
|
11
|
+
it('Should return valid date', () => {
|
|
12
|
+
const result = getDateObject('2025-05-21 12:34');
|
|
13
|
+
expect(result?.toISOString()).toStrictEqual(new Date(2025, 4, 21, 12, 34).toISOString());
|
|
14
|
+
});
|
|
15
|
+
});
|
|
10
16
|
describe('Backend date format (2025-05-21)', () => {
|
|
11
17
|
it('Should return valid date', () => {
|
|
12
18
|
const date = '2025-05-21';
|
|
13
19
|
const result = getDateObject(date);
|
|
14
|
-
expect(result?.toISOString()).toStrictEqual(new Date(
|
|
20
|
+
expect(result?.toISOString()).toStrictEqual(new Date(2025, 4, 21).toISOString());
|
|
21
|
+
});
|
|
22
|
+
it('Should preserve the calendar day in a negative UTC offset', () => {
|
|
23
|
+
vi.stubEnv('TZ', 'America/New_York');
|
|
24
|
+
try {
|
|
25
|
+
expect(getDateObject('2025-05-21')?.getDate()).toBe(21);
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
vi.unstubAllEnvs();
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
describe('US date format (05/21/2025)', () => {
|
|
33
|
+
it('Should return valid date', () => {
|
|
34
|
+
const result = getDateObject('05/21/2025');
|
|
35
|
+
expect(result?.toISOString()).toStrictEqual(new Date(2025, 4, 21).toISOString());
|
|
15
36
|
});
|
|
16
37
|
});
|
|
17
38
|
describe('ISO format (2025-09-03T13:32:21.582Z)', () => {
|
|
@@ -24,6 +45,6 @@ describe('ISO format (2025-09-03T13:32:21.582Z)', () => {
|
|
|
24
45
|
describe('Invalid values', () => {
|
|
25
46
|
it('Should not return any date', () => {
|
|
26
47
|
const date = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
|
|
27
|
-
expect(getDateObject(date)).
|
|
48
|
+
expect(getDateObject(date)).toBeNull();
|
|
28
49
|
});
|
|
29
50
|
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a date string into a Date object.
|
|
3
|
+
* Supports ISO format, backend datetime format with and without seconds, and US date format.
|
|
4
|
+
* Returns an invalid Date object if the input does not match any supported format.
|
|
5
|
+
*/
|
|
6
|
+
export declare const parseDate: (input: string) => Date;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { parse, parseISO } from 'date-fns';
|
|
2
|
+
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}(?:T.*)?$/;
|
|
3
|
+
const DATETIME_REGEX = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
|
4
|
+
const DATETIME_WITHOUT_SECONDS_REGEX = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
|
|
5
|
+
const US_DATE_REGEX = /^\d{2}\/\d{2}\/\d{4}$/;
|
|
6
|
+
/**
|
|
7
|
+
* Parses a date string into a Date object.
|
|
8
|
+
* Supports ISO format, backend datetime format with and without seconds, and US date format.
|
|
9
|
+
* Returns an invalid Date object if the input does not match any supported format.
|
|
10
|
+
*/
|
|
11
|
+
export const parseDate = (input) => {
|
|
12
|
+
if (ISO_DATE_REGEX.test(input))
|
|
13
|
+
return parseISO(input);
|
|
14
|
+
if (DATETIME_REGEX.test(input))
|
|
15
|
+
return parse(input, 'yyyy-MM-dd HH:mm:ss', new Date());
|
|
16
|
+
if (DATETIME_WITHOUT_SECONDS_REGEX.test(input))
|
|
17
|
+
return parse(input, 'yyyy-MM-dd HH:mm', new Date());
|
|
18
|
+
if (US_DATE_REGEX.test(input))
|
|
19
|
+
return parse(input, 'MM/dd/yyyy', new Date());
|
|
20
|
+
return new Date(Number.NaN);
|
|
21
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Get the last specific day of the week before a given date.
|
|
3
|
+
*
|
|
4
|
+
* Example usage:
|
|
5
|
+
* Returns the last Monday before September 15, 2023, ie. September 11, 2023
|
|
6
|
+
* const lastMonday = getLastSpecificDate(new Date('2023-09-15'))
|
|
7
|
+
*
|
|
8
|
+
* Default dayOfWeek is Monday (6).
|
|
9
|
+
*
|
|
10
|
+
* Note: this is a domain-specific numbering used for "find previous specific day"
|
|
11
|
+
* calculation, not JS `getDay()` or ISO day numbering.
|
|
12
|
+
*
|
|
13
|
+
* List of days of the week:
|
|
14
|
+
* Sunday = 7
|
|
15
|
+
* Monday = 6
|
|
16
|
+
* Thursday = 5
|
|
17
|
+
* Wednesday = 4
|
|
18
|
+
* Tuesday = 3
|
|
19
|
+
* Friday = 2
|
|
20
|
+
* Saturday = 1
|
|
21
|
+
*/
|
|
22
|
+
export declare const getLastSpecificDate: (input: unknown, dayOfWeek?: number) => Date | null;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { isNullOrUndefined } from '../../validators/isNullOrUndefined/isNullOrUndefined.js';
|
|
2
|
+
import { isObject } from '../../validators/isObject/isObject.js';
|
|
3
|
+
import { isString } from '../../validators/isString/isString.js';
|
|
4
|
+
import { isValidDateInstance } from '../../validators/isValidDateInstance/isValidDateInstance.js';
|
|
5
|
+
import { getDateObject } from '../getDateObject/getDateObject.js';
|
|
6
|
+
import { getSpecificDate } from './utils/getSpecificDate.js';
|
|
7
|
+
/**
|
|
8
|
+
* Get the last specific day of the week before a given date.
|
|
9
|
+
*
|
|
10
|
+
* Example usage:
|
|
11
|
+
* Returns the last Monday before September 15, 2023, ie. September 11, 2023
|
|
12
|
+
* const lastMonday = getLastSpecificDate(new Date('2023-09-15'))
|
|
13
|
+
*
|
|
14
|
+
* Default dayOfWeek is Monday (6).
|
|
15
|
+
*
|
|
16
|
+
* Note: this is a domain-specific numbering used for "find previous specific day"
|
|
17
|
+
* calculation, not JS `getDay()` or ISO day numbering.
|
|
18
|
+
*
|
|
19
|
+
* List of days of the week:
|
|
20
|
+
* Sunday = 7
|
|
21
|
+
* Monday = 6
|
|
22
|
+
* Thursday = 5
|
|
23
|
+
* Wednesday = 4
|
|
24
|
+
* Tuesday = 3
|
|
25
|
+
* Friday = 2
|
|
26
|
+
* Saturday = 1
|
|
27
|
+
*/
|
|
28
|
+
export const getLastSpecificDate = (input, dayOfWeek = 6) => {
|
|
29
|
+
const previousDayCode = dayOfWeek < 1 || dayOfWeek > 7 ? 6 : dayOfWeek; // Default to Monday if invalid dayOfWeek is provided
|
|
30
|
+
if (isNullOrUndefined(input))
|
|
31
|
+
return null;
|
|
32
|
+
if (input instanceof Date)
|
|
33
|
+
return isValidDateInstance(input) ? getSpecificDate(input, previousDayCode) : null;
|
|
34
|
+
if (isObject(input))
|
|
35
|
+
return null;
|
|
36
|
+
if (!isString(input))
|
|
37
|
+
return null;
|
|
38
|
+
const date = getDateObject(input);
|
|
39
|
+
if (isNullOrUndefined(date))
|
|
40
|
+
return null;
|
|
41
|
+
return getSpecificDate(date, previousDayCode);
|
|
42
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|