@arkyn/shared 3.0.1-beta.21 → 3.0.1-beta.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.
Files changed (35) hide show
  1. package/README.md +452 -67
  2. package/package.json +21 -2
  3. package/src/formats/formatDate.ts +0 -92
  4. package/src/formats/formatJsonObject.ts +0 -90
  5. package/src/formats/formatJsonString.ts +0 -50
  6. package/src/formats/formatToCapitalizeFirstWordLetter.ts +0 -46
  7. package/src/formats/formatToCep.ts +0 -39
  8. package/src/formats/formatToCnpj.ts +0 -40
  9. package/src/formats/formatToCpf.ts +0 -40
  10. package/src/formats/formatToCpfCnpj.ts +0 -38
  11. package/src/formats/formatToCurrency.ts +0 -63
  12. package/src/formats/formatToDate.ts +0 -70
  13. package/src/formats/formatToEllipsis.ts +0 -25
  14. package/src/formats/formatToHiddenDigits.ts +0 -92
  15. package/src/formats/formatToPhone.ts +0 -170
  16. package/src/generators/generateColorByString.ts +0 -33
  17. package/src/generators/generateId.ts +0 -61
  18. package/src/generators/generateSlug.ts +0 -31
  19. package/src/index.ts +0 -37
  20. package/src/services/calculateCardInstallment.ts +0 -73
  21. package/src/services/ensureQuotes.ts +0 -25
  22. package/src/services/maskSensitiveData.ts +0 -68
  23. package/src/services/removeCurrencySymbols.ts +0 -29
  24. package/src/services/removeNonNumeric.ts +0 -20
  25. package/src/services/stripHtmlTags.ts +0 -20
  26. package/src/services/truncateLargeFields.ts +0 -69
  27. package/src/validations/validateCep.ts +0 -41
  28. package/src/validations/validateCnpj.ts +0 -65
  29. package/src/validations/validateCpf.ts +0 -62
  30. package/src/validations/validateDate.ts +0 -86
  31. package/src/validations/validatePassword.ts +0 -41
  32. package/src/validations/validatePhone.ts +0 -50
  33. package/src/validations/validateRg.ts +0 -37
  34. package/tsconfig.json +0 -20
  35. package/vitest.config.ts +0 -5
@@ -1,170 +0,0 @@
1
- import { countries } from "@arkyn/templates";
2
-
3
- import { removeNonNumeric } from "../services/removeNonNumeric";
4
-
5
- type CountryType = {
6
- name: string;
7
- code: string;
8
- iso: string;
9
- prefix: null | string;
10
- flag: string;
11
- mask: string;
12
- };
13
-
14
- type FormatToPhoneFunction = (prop: string) => string;
15
-
16
- function getMask(value: string): "NINE" | "EIGTH" {
17
- const mask = value.length > 10 ? "NINE" : "EIGTH";
18
- return mask;
19
- }
20
-
21
- const TYPES = {
22
- EIGTH: "(99) 9999-9999",
23
- NINE: "(99) 99999-9999",
24
- };
25
-
26
- const MAX_LENGTH = removeNonNumeric(TYPES.NINE).length;
27
-
28
- function applyMask(value: string, maskPattern: string) {
29
- let result = "";
30
- let digitIndex = 0;
31
-
32
- for (let i = 0; i < maskPattern.length; i++) {
33
- if (maskPattern[i] === "9") {
34
- if (digitIndex < value.length) {
35
- result += value[digitIndex];
36
- digitIndex++;
37
- } else {
38
- break;
39
- }
40
- } else {
41
- if (digitIndex < value.length) {
42
- result += maskPattern[i];
43
- } else {
44
- break;
45
- }
46
- }
47
- }
48
-
49
- return result;
50
- }
51
-
52
- function formatPhoneNumber(phoneNumber: string, country: CountryType): string {
53
- if (country.code === "+55") {
54
- let value = removeNonNumeric(phoneNumber);
55
- const mask = getMask(value);
56
-
57
- let nextLength = value.length;
58
- if (nextLength > MAX_LENGTH) return value;
59
-
60
- value = applyMask(value, TYPES[mask] as "EIGTH" | "NINE");
61
- return value;
62
- }
63
-
64
- const mask = country.mask;
65
- let formattedNumber = mask;
66
-
67
- if (country.prefix) {
68
- const prefixRegex = /\$+/g;
69
- formattedNumber = formattedNumber.replace(prefixRegex, country.prefix);
70
- }
71
-
72
- for (
73
- let i = 0, j = 0;
74
- i < formattedNumber.length && j < phoneNumber.length;
75
- i++
76
- ) {
77
- if (formattedNumber[i] === "_") {
78
- formattedNumber =
79
- formattedNumber.substring(0, i) +
80
- phoneNumber[j] +
81
- formattedNumber.substring(i + 1);
82
- j++;
83
- }
84
- }
85
-
86
- return formattedNumber;
87
- }
88
-
89
- function getCountryWithPrefixCode(countryCode: string, prefix: string) {
90
- const country = countries.find(
91
- (country) => country.code === countryCode && country.prefix === prefix
92
- );
93
-
94
- if (!country) throw new Error("Invalid country code or prefix");
95
-
96
- if (country.prefix !== prefix) {
97
- throw new Error("Invalid country code or prefix");
98
- }
99
-
100
- if (!country.prefix) {
101
- throw new Error("Invalid country code or prefix");
102
- }
103
- return country;
104
- }
105
-
106
- function getCountryWithoutPrefixCode(countryCode: string) {
107
- const country = countries.find((country) => country.code === countryCode);
108
- if (!country) throw new Error("Invalid country code");
109
- if (country.prefix) throw new Error("Invalid country code");
110
- return country;
111
- }
112
-
113
- /**
114
- * Formats a phone number string based on the provided country code and optional prefix.
115
- *
116
- * The input string should follow the format: `"<countryCode>-<prefix> <phoneNumber>"` or `"<countryCode> <phoneNumber>"`.
117
- * The function determines the appropriate formatting mask based on the country and applies it to the phone number.
118
- *
119
- * @param prop - The phone number string to be formatted. It must include the country code and optionally a prefix.
120
- * Example formats:
121
- * - "+55 32912345678"
122
- * - "+1 1234567890"
123
- *
124
- * @returns The formatted phone number string based on the country's formatting rules.
125
- *
126
- * @throws {Error} If the input phone number does not match the expected format.
127
- * @throws {Error} If the country code or phone number is missing from the input string.
128
- * @throws {Error} If the provided country code and prefix combination is invalid.
129
- * @throws {Error} If the provided country code is invalid.
130
- * @throws {Error} If the provided country code has a prefix but none is supplied in the input.
131
- *
132
- * @example
133
- * ```typescript
134
- * import { formatToPhone } from "./formatToPhone";
135
- *
136
- * const formattedPhone1 = formatToPhone("+55 11912345678");
137
- * console.log(formattedPhone1); // Output: "(11) 91234-5678" (brazilian phone number format)
138
- *
139
- * const formattedPhone2 = formatToPhone("+1-123 4567890");
140
- * console.log(formattedPhone2); // Output: "(123) 456-7890" (us phone number format)
141
- * ```
142
- */
143
-
144
- const formatToPhone: FormatToPhoneFunction = (prop) => {
145
- const phoneRegex = /^\+\d{1,4}(-\d{1,4})? \d+$/;
146
-
147
- if (!phoneRegex.test(prop)) {
148
- throw new Error(
149
- "Invalid phone number format. Expected format: +<countryCode>-<optionalPrefix> <phoneNumber>"
150
- );
151
- }
152
-
153
- const countryCode = prop.split(" ")[0].split("-")[0];
154
- const prefixCode = prop.split(" ")[0].split("-")[1];
155
- const phoneNumber = prop.split(" ")[1];
156
-
157
- if (!countryCode || !phoneNumber) {
158
- throw new Error("Invalid phone number format");
159
- }
160
-
161
- if (prefixCode) {
162
- const country = getCountryWithPrefixCode(countryCode, prefixCode);
163
- return formatPhoneNumber(phoneNumber, country);
164
- }
165
-
166
- const country = getCountryWithoutPrefixCode(countryCode);
167
- return formatPhoneNumber(phoneNumber, country);
168
- };
169
-
170
- export { formatToPhone };
@@ -1,33 +0,0 @@
1
- type GenerateColorByStringFunction = (prop: string) => string;
2
-
3
- /**
4
- * Generates a hexadecimal color code based on the input string.
5
- * The function creates a hash from the string and uses it to calculate
6
- * RGB values, which are then converted to a hexadecimal color code.
7
- *
8
- * @param prop - The input string used to generate the color.
9
- * @returns A hexadecimal color code (e.g., "#a1b2c3") derived from the input string.
10
- * @example
11
- * const color = generateColorByString("example");
12
- * console.log(color); // Outputs a consistent hex color like "#5e8f9a"
13
- */
14
-
15
- const generateColorByString: GenerateColorByStringFunction = (prop) => {
16
- var hash = 0;
17
-
18
- for (var i = 0; i < prop.length; i++) {
19
- hash = prop.charCodeAt(i) + ((hash << 5) - hash);
20
- }
21
-
22
- var red = (hash & 0xff0000) >> 16;
23
- var green = (hash & 0x00ff00) >> 8;
24
- var blue = hash & 0x0000ff;
25
-
26
- var redHex = red.toString(16).padStart(2, "0");
27
- var greenHex = green.toString(16).padStart(2, "0");
28
- var blueHex = blue.toString(16).padStart(2, "0");
29
-
30
- return "#" + redHex + greenHex + blueHex;
31
- };
32
-
33
- export { generateColorByString };
@@ -1,61 +0,0 @@
1
- import { v4, v7 } from "uuid";
2
-
3
- function hexToBin(hex: string) {
4
- hex = hex.replace(/-/g, "");
5
- const buffer = new Uint8Array(hex.length / 2);
6
-
7
- for (let i = 0; i < hex.length; i += 2) {
8
- buffer[i / 2] = parseInt(hex.substring(i, i + 2), 16);
9
- }
10
-
11
- return buffer;
12
- }
13
-
14
- function uuidV4() {
15
- const uuid = v4();
16
- return { text: uuid, binary: hexToBin(uuid) };
17
- }
18
-
19
- function uuidV7() {
20
- const uuid = v7();
21
- return { text: uuid, binary: hexToBin(uuid) };
22
- }
23
-
24
- /**
25
- * Generates a unique identifier (UUID) in the specified format and type.
26
- *
27
- * @param type - The desired output type of the UUID. Can be:
28
- * - `"text"`: Returns the UUID as a string.
29
- * - `"binary"`: Returns the UUID as a `Uint8Array` in binary format.
30
- * @param format - The version of the UUID to generate. Can be:
31
- * - `"v4"`: Generates a random UUID (version 4).
32
- * - `"v7"`: Generates a time-ordered UUID (version 7).
33
- * @returns The generated UUID in the specified type and format.
34
- * - If `type` is `"text"`, a string representation of the UUID is returned.
35
- * - If `type` is `"binary"`, a `Uint8Array` representation of the UUID is returned.
36
- * @throws {Error} If an invalid `type` or `format` is provided.
37
- *
38
- * @example
39
- * // Generate a version 4 UUID as a string
40
- * const idTextV4 = generateId("text", "v4");
41
- * console.log(idTextV4); // e.g., "550e8400-e29b-41d4-a716-446655440000"
42
- *
43
- * @example
44
- * // Generate a version 7 UUID as binary
45
- * const idBinaryV7 = generateId("binary", "v7");
46
- * console.log(idBinaryV7); // Uint8Array([...])
47
- */
48
- function generateId(type: "text", format: "v4" | "v7"): string;
49
- function generateId(type: "binary", format: "v4" | "v7"): Uint8Array;
50
- function generateId(
51
- type: "text" | "binary",
52
- format: "v4" | "v7"
53
- ): string | Uint8Array {
54
- if (type === "text" && format === "v4") return uuidV4().text;
55
- if (type === "binary" && format === "v4") return uuidV4().binary;
56
- if (type === "text" && format === "v7") return uuidV7().text;
57
- if (type === "binary" && format === "v7") return uuidV7().binary;
58
- throw new Error("Invalid type or format");
59
- }
60
-
61
- export { generateId };
@@ -1,31 +0,0 @@
1
- /**
2
- * Generates a URL-friendly slug from a given string.
3
- *
4
- * The function performs the following transformations:
5
- * - Normalizes the string to remove diacritical marks (e.g., accents).
6
- * - Removes non-alphanumeric characters except for spaces and hyphens.
7
- * - Replaces spaces with hyphens.
8
- * - Converts the string to lowercase.
9
- * - Collapses multiple consecutive hyphens into a single hyphen.
10
- * - Trims leading and trailing hyphens.
11
- *
12
- * @param string - The input string to be converted into a slug.
13
- * @returns A URL-friendly slug derived from the input string.
14
- */
15
-
16
- function generateSlug(prop: string) {
17
- let slug = prop.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
18
-
19
- slug = slug
20
- .replace(/[^\w\s-]/g, "")
21
- .replace(/\s+/g, "-")
22
- .toLowerCase();
23
-
24
- slug = slug.replace(/-{2,}/g, "-");
25
-
26
- slug = slug.replace(/^-+|-+$/g, "");
27
-
28
- return slug;
29
- }
30
-
31
- export { generateSlug };
package/src/index.ts DELETED
@@ -1,37 +0,0 @@
1
- // formats
2
- export { formatDate } from "./formats/formatDate";
3
- export { formatJsonObject } from "./formats/formatJsonObject";
4
- export { formatJsonString } from "./formats/formatJsonString";
5
- export { formatToCapitalizeFirstWordLetter } from "./formats/formatToCapitalizeFirstWordLetter";
6
- export { formatToCep } from "./formats/formatToCep";
7
- export { formatToCnpj } from "./formats/formatToCnpj";
8
- export { formatToCpf } from "./formats/formatToCpf";
9
- export { formatToCpfCnpj } from "./formats/formatToCpfCnpj";
10
- export { formatToCurrency } from "./formats/formatToCurrency";
11
- export { formatToDate } from "./formats/formatToDate";
12
- export { formatToEllipsis } from "./formats/formatToEllipsis";
13
- export { formatToHiddenDigits } from "./formats/formatToHiddenDigits";
14
- export { formatToPhone } from "./formats/formatToPhone";
15
-
16
- // generators
17
- export { generateColorByString } from "./generators/generateColorByString";
18
- export { generateId } from "./generators/generateId";
19
- export { generateSlug } from "./generators/generateSlug";
20
-
21
- // services
22
- export { calculateCardInstallment } from "./services/calculateCardInstallment";
23
- export { ensureQuotes } from "./services/ensureQuotes";
24
- export { maskSensitiveData } from "./services/maskSensitiveData";
25
- export { removeCurrencySymbols } from "./services/removeCurrencySymbols";
26
- export { removeNonNumeric } from "./services/removeNonNumeric";
27
- export { stripHtmlTags } from "./services/stripHtmlTags";
28
- export { truncateLargeFields } from "./services/truncateLargeFields";
29
-
30
- // utils
31
- export { validateCep } from "./validations/validateCep";
32
- export { validateCnpj } from "./validations/validateCnpj";
33
- export { validateCpf } from "./validations/validateCpf";
34
- export { validateDate } from "./validations/validateDate";
35
- export { validatePassword } from "./validations/validatePassword";
36
- export { validatePhone } from "./validations/validatePhone";
37
- export { validateRg } from "./validations/validateRg";
@@ -1,73 +0,0 @@
1
- type CalculateCardInstallmentFunction = (props: {
2
- cashPrice: number;
3
- numberInstallments: number;
4
- fees?: number;
5
- }) => {
6
- totalPrice: number;
7
- installmentPrice: number;
8
- };
9
-
10
- /**
11
- * Calculates the installment price and total price for a card payment plan.
12
- *
13
- * @remarks
14
- * **Important:** When the interest amount (`fees`) is equal to 0 or the number of installments (`numberInstallments`) is equal to 1, no interest will be charged.
15
- *
16
- * @throws Will throw an error if the number of installments is less than or equal to 0.
17
- * @throws Will throw an error if the fees are less than 0.
18
- *
19
- * @param props - The input parameters for the calculation.
20
- * @param props.cashPrice - The total cash price of the product or service.
21
- * @param props.numberInstallments - The number of installments for the payment plan.
22
- * @param props.fees - The interest rate per installment (default is 0.0349).
23
- *
24
- * @returns An object containing:
25
- * - `totalPrice`: The total price to be paid, rounded to two decimal places.
26
- * - `installmentPrice`: The price of each installment, rounded to two decimal places.
27
- *
28
- * @example
29
- * ```typescript
30
- * const result = calculateCardInstallment({
31
- * cashPrice: 1000,
32
- * numberInstallments: 12,
33
- * fees: 0.02,
34
- * });
35
- * console.log(result);
36
- * // Output: { totalPrice: 1124.62, installmentPrice: 93.72 }
37
- * ```
38
- */
39
-
40
- const calculateCardInstallment: CalculateCardInstallmentFunction = (props) => {
41
- const { cashPrice, numberInstallments, fees = 0.0349 } = props;
42
-
43
- if (fees === 0 || numberInstallments === 1) {
44
- return {
45
- totalPrice: cashPrice,
46
- installmentPrice: cashPrice / numberInstallments,
47
- };
48
- }
49
-
50
- if (numberInstallments <= 0) {
51
- throw new Error("Number of installments must be greater than 0");
52
- }
53
-
54
- if (fees < 0) {
55
- throw new Error("Fees must be greater than or equal to 0");
56
- }
57
-
58
- let installmentPrice = 0;
59
- let totalPrice = 0;
60
-
61
- let numerator = Math.pow(1 + fees, numberInstallments) * fees;
62
- let denominator = Math.pow(1 + fees, numberInstallments) - 1;
63
-
64
- installmentPrice = cashPrice * (numerator / denominator);
65
- totalPrice = numberInstallments * installmentPrice;
66
-
67
- return {
68
- totalPrice: +totalPrice.toFixed(2),
69
- installmentPrice: +installmentPrice.toFixed(2),
70
- };
71
- };
72
-
73
- export { calculateCardInstallment };
@@ -1,25 +0,0 @@
1
- type EnsureQuotesFunction = (rawValue: string) => string;
2
-
3
- /**
4
- * Ensures that a given rawValue string is enclosed in quotes.
5
- *
6
- * This function checks if the input string is already enclosed in either single
7
- * quotes (`'`) or double quotes (`"`). If the string is already quoted, it is
8
- * returned as-is. Otherwise, the function wraps the string in double quotes.
9
- *
10
- * @param url - The URL string to be checked and potentially quoted.
11
- * @returns The input string, either unchanged if it is already quoted, or wrapped in double quotes.
12
- */
13
-
14
- const ensureQuotes: EnsureQuotesFunction = (rawValue) => {
15
- const hasSingleQuotes = rawValue.startsWith("'") && rawValue.endsWith("'");
16
- const hasDoubleQuotes = rawValue.startsWith('"') && rawValue.endsWith('"');
17
-
18
- if (hasSingleQuotes || hasDoubleQuotes) {
19
- return rawValue;
20
- }
21
-
22
- return `"${rawValue}"`;
23
- };
24
-
25
- export { ensureQuotes };
@@ -1,68 +0,0 @@
1
- type MaskSensitiveDataFunction = (
2
- jsonString: string,
3
- sensitiveKeys?: string[]
4
- ) => string;
5
-
6
- /**
7
- * Masks sensitive data in a JSON string by replacing the values of specified keys with "****".
8
- *
9
- * @param jsonString - The JSON string to be processed.
10
- * @param sensitiveKeys - An array of keys whose values should be masked. Defaults to `["password", "confirmPassword", "creditCard"]`.
11
- * @returns A JSON string with sensitive data masked. If the input is not a valid JSON string, it returns the original string.
12
- *
13
- * @example
14
- * ```typescript
15
- * const jsonString = JSON.stringify({
16
- * username: "user123",
17
- * password: "secret",
18
- * profile: {
19
- * creditCard: "1234-5678-9012-3456",
20
- * },
21
- * });
22
- *
23
- * const result = maskSensitiveData(jsonString, ["password", "creditCard"]);
24
- * console.log(result);
25
- * // Output: '{"username":"user123","password":"****","profile":{"creditCard":"****"}}'
26
- * ```
27
- */
28
-
29
- const maskSensitiveData: MaskSensitiveDataFunction = (
30
- jsonString,
31
- sensitiveKeys = ["password", "confirmPassword", "creditCard"]
32
- ) => {
33
- function maskValue(key: string, value: any): any {
34
- if (sensitiveKeys.includes(key)) return "****";
35
- return value;
36
- }
37
-
38
- function recursiveMask(obj: any): any {
39
- if (Array.isArray(obj)) {
40
- return obj.map((item) => recursiveMask(item));
41
- } else if (obj !== null && typeof obj === "object") {
42
- return Object.keys(obj).reduce((acc, key) => {
43
- let value = obj[key];
44
- if (typeof value === "string") {
45
- try {
46
- const parsedValue = JSON.parse(value);
47
- if (typeof parsedValue === "object") {
48
- value = JSON.stringify(recursiveMask(parsedValue));
49
- }
50
- } catch (e) {}
51
- }
52
- acc[key] = recursiveMask(maskValue(key, value));
53
- return acc;
54
- }, {} as any);
55
- }
56
- return obj;
57
- }
58
-
59
- try {
60
- const jsonObject = JSON.parse(jsonString);
61
- const maskedObject = recursiveMask(jsonObject);
62
- return JSON.stringify(maskedObject);
63
- } catch (error) {
64
- return jsonString;
65
- }
66
- };
67
-
68
- export { maskSensitiveData };
@@ -1,29 +0,0 @@
1
- type RemoveCurrencySymbolsFunction = (formattedValue: string) => string;
2
-
3
- /**
4
- * Removes currency symbols from a given formatted string.
5
- *
6
- * This function takes a string that may contain currency symbols
7
- * and removes them using a regular expression. The resulting string
8
- * is also trimmed of any leading or trailing whitespace.
9
- *
10
- * @param formattedValue - The input string containing currency symbols.
11
- * @returns A string with all currency symbols removed and trimmed of whitespace.
12
- *
13
- * @example
14
- * removeCurrencySymbols("R$13,45"); // "13,45"
15
- * removeCurrencySymbols("$123.45"); // "123.45"
16
- * removeCurrencySymbols("€99.99"); // "99.99"
17
- * removeCurrencySymbols("¥1,000"); // "1,000"
18
- * removeCurrencySymbols("123.45"); // "123.45" (no symbols to remove)
19
- */
20
-
21
- const removeCurrencySymbols: RemoveCurrencySymbolsFunction = (
22
- formattedValue
23
- ) => {
24
- return formattedValue
25
- .replace(/(?:R\$|\p{Sc}|[$€¥£])/gu, "") // Inclui "R$" e outros símbolos comuns
26
- .trim();
27
- };
28
-
29
- export { removeCurrencySymbols };
@@ -1,20 +0,0 @@
1
- type RemoveNonNumericFunction = (formattedValue: string) => string;
2
-
3
- /**
4
- * Removes all non-numeric characters from a given string.
5
- *
6
- * @param prop - The input string from which non-numeric characters will be removed.
7
- * @returns A new string containing only numeric characters from the input.
8
- *
9
- * @example
10
- * ```typescript
11
- * const result = removeNonNumeric("abc123def456");
12
- * console.log(result); // Output: "123456"
13
- * ```
14
- */
15
-
16
- const removeNonNumeric: RemoveNonNumericFunction = (prop) => {
17
- return prop.replace(/[^0-9]/g, "");
18
- };
19
-
20
- export { removeNonNumeric };
@@ -1,20 +0,0 @@
1
- type StripHtmlTagsFunction = (rawHtml: string) => string;
2
-
3
- /**
4
- * Strips HTML tags from a string.
5
- *
6
- * This function removes all HTML tags from the provided string by replacing any content
7
- * that matches the HTML tag pattern with an empty string.
8
- *
9
- * @param rawHtml - The HTML string to be processed
10
- * @returns The input string with all HTML tags removed
11
- *
12
- * @example
13
- * stripHtmlTags("<p>Hello <strong>World</strong></p>"); // "Hello World"
14
- */
15
-
16
- const stripHtmlTags: StripHtmlTagsFunction = (rawHtml) => {
17
- return rawHtml.replace(/<\/?[^>]+(>|$)/g, "");
18
- };
19
-
20
- export { stripHtmlTags };
@@ -1,69 +0,0 @@
1
- type TruncateLargeFieldsFunction = (
2
- jsonString: string,
3
- maxLength?: number
4
- ) => string;
5
-
6
- /**
7
- * Truncates large string fields in a JSON string to a specified maximum length.
8
- *
9
- * This function parses a JSON string, traverses its structure recursively, and truncates
10
- * any string fields that exceed the specified maximum length. If a string field is truncated,
11
- * it is replaced with a message indicating the original length of the field.
12
- *
13
- * @param jsonString - The JSON string to process.
14
- * @param maxLength - The maximum allowed length for string fields. Defaults to 1000.
15
- * @returns A JSON string with large string fields truncated.
16
- *
17
- * @throws {Error} Throws an error if the input is not a valid JSON string.
18
- *
19
- * @example
20
- * ```typescript
21
- * const json = JSON.stringify({
22
- * name: "John",
23
- * description: "A very long description that exceeds the maximum length...",
24
- * nested: {
25
- * details: "Another long string that needs truncation."
26
- * }
27
- * });
28
- *
29
- * const result = truncateLargeFields(json, 50);
30
- * console.log(result);
31
- * // Output: '{"name":"John","description":"To large information: field as 57 characters","nested":{"details":"To large information: field as 43 characters"}}'
32
- * ```
33
- */
34
-
35
- const truncateLargeFields: TruncateLargeFieldsFunction = (
36
- jsonString,
37
- maxLength = 1000
38
- ) => {
39
- function truncateValue(value: any): any {
40
- if (typeof value === "string" && value.length > maxLength) {
41
- return `To large information: field as ${value.length} characters`;
42
- }
43
- return value;
44
- }
45
-
46
- function recursiveTruncate(obj: any): any {
47
- if (Array.isArray(obj)) {
48
- return obj.map((item) => recursiveTruncate(item)); // Corrigido para processar elementos do array
49
- } else if (obj !== null && typeof obj === "object") {
50
- return Object.fromEntries(
51
- Object.entries(obj).map(([key, value]) => [
52
- key,
53
- recursiveTruncate(value), // Corrigido para aplicar recursão corretamente
54
- ])
55
- );
56
- }
57
- return truncateValue(obj); // Corrigido para truncar valores diretamente
58
- }
59
-
60
- try {
61
- const parsedJson = JSON.parse(jsonString);
62
- const truncatedJson = recursiveTruncate(parsedJson);
63
- return JSON.stringify(truncatedJson);
64
- } catch (error) {
65
- throw new Error("Invalid JSON string");
66
- }
67
- };
68
-
69
- export { truncateLargeFields };
@@ -1,41 +0,0 @@
1
- import { removeNonNumeric } from "../services/removeNonNumeric";
2
-
3
- type ValidateCepFunction = (rawCep: string) => boolean;
4
-
5
- /**
6
- * Removes all non-digit characters from the CEP.
7
- * @param cep - Raw CEP string.
8
- * @returns Only numeric characters.
9
- */
10
-
11
- /**
12
- * Validates a Brazilian CEP (Código de Endereçamento Postal).
13
- *
14
- * A valid CEP has 8 numeric digits.
15
- *
16
- * @param rawCep - CEP string, may include formatting (e.g., "12345-678").
17
- * @returns `true` if the CEP is valid, otherwise `false`.
18
- *
19
- * @example
20
- * ```ts
21
- * validateCep("12345-678"); // true
22
- * validateCep("12345678"); // true
23
- * validateCep("ABCDE-123"); // false
24
- * ```
25
- */
26
-
27
- const validateCep: ValidateCepFunction = (rawCep) => {
28
- if (!rawCep) return false;
29
-
30
- const validFormat = /^[0-9-]+$/.test(rawCep);
31
- if (!validFormat) return false;
32
-
33
- const cep = removeNonNumeric(rawCep);
34
-
35
- const CEP_LENGTH = 8;
36
- const isOnlyDigits = /^\d{8}$/.test(cep);
37
-
38
- return cep.length === CEP_LENGTH && isOnlyDigits;
39
- };
40
-
41
- export { validateCep };