@arkyn/shared 1.4.52 → 1.4.55

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 (139) hide show
  1. package/dist/formats/formatDate.d.ts +43 -0
  2. package/dist/formats/formatDate.d.ts.map +1 -0
  3. package/dist/formats/formatDate.js +77 -0
  4. package/dist/formats/formatJsonObject.d.ts +31 -1
  5. package/dist/formats/formatJsonObject.d.ts.map +1 -1
  6. package/dist/formats/formatJsonObject.js +67 -26
  7. package/dist/formats/formatJsonString.d.ts +37 -1
  8. package/dist/formats/formatJsonString.d.ts.map +1 -1
  9. package/dist/formats/formatJsonString.js +38 -4
  10. package/dist/formats/formatToCep.d.ts +27 -1
  11. package/dist/formats/formatToCep.d.ts.map +1 -1
  12. package/dist/formats/formatToCep.js +31 -6
  13. package/dist/formats/formatToCnpj.d.ts +30 -0
  14. package/dist/formats/formatToCnpj.d.ts.map +1 -0
  15. package/dist/formats/formatToCnpj.js +35 -0
  16. package/dist/formats/formatToCpf.d.ts +30 -0
  17. package/dist/formats/formatToCpf.d.ts.map +1 -0
  18. package/dist/formats/formatToCpf.js +35 -0
  19. package/dist/formats/formatToCpfCnpj.d.ts +22 -1
  20. package/dist/formats/formatToCpfCnpj.d.ts.map +1 -1
  21. package/dist/formats/formatToCpfCnpj.js +27 -7
  22. package/dist/formats/formatToCurrency.d.ts +29 -0
  23. package/dist/formats/formatToCurrency.d.ts.map +1 -0
  24. package/dist/formats/formatToCurrency.js +41 -0
  25. package/dist/formats/formatToEllipsis.d.ts +14 -1
  26. package/dist/formats/formatToEllipsis.d.ts.map +1 -1
  27. package/dist/formats/formatToEllipsis.js +20 -3
  28. package/dist/formats/formatToHiddenDigits.d.ts +30 -2
  29. package/dist/formats/formatToHiddenDigits.d.ts.map +1 -1
  30. package/dist/formats/formatToHiddenDigits.js +49 -3
  31. package/dist/formats/formatToPhone.d.ts +32 -1
  32. package/dist/formats/formatToPhone.d.ts.map +1 -1
  33. package/dist/formats/formatToPhone.js +128 -6
  34. package/dist/generators/generateColorByString.d.ts +13 -1
  35. package/dist/generators/generateColorByString.d.ts.map +1 -1
  36. package/dist/generators/generateColorByString.js +15 -4
  37. package/dist/generators/generateId.d.ts +26 -4
  38. package/dist/generators/generateId.d.ts.map +1 -1
  39. package/dist/generators/generateId.js +11 -5
  40. package/dist/generators/generateSlug.d.ts +15 -1
  41. package/dist/generators/generateSlug.d.ts.map +1 -1
  42. package/dist/generators/generateSlug.js +16 -2
  43. package/dist/index.d.ts +7 -10
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +7 -15
  46. package/dist/regex/index.d.ts +6 -0
  47. package/dist/regex/index.d.ts.map +1 -0
  48. package/dist/regex/index.js +4 -0
  49. package/dist/services/calculateCardInstallment.d.ts +31 -5
  50. package/dist/services/calculateCardInstallment.d.ts.map +1 -1
  51. package/dist/services/calculateCardInstallment.js +52 -11
  52. package/dist/services/maskSensitiveData.d.ts +24 -1
  53. package/dist/services/maskSensitiveData.d.ts.map +1 -1
  54. package/dist/services/maskSensitiveData.js +24 -2
  55. package/dist/services/removeCurrencySymbols.d.ts +20 -0
  56. package/dist/services/removeCurrencySymbols.d.ts.map +1 -0
  57. package/dist/services/removeCurrencySymbols.js +23 -0
  58. package/dist/services/removeNonNumeric.d.ts +15 -0
  59. package/dist/services/removeNonNumeric.d.ts.map +1 -0
  60. package/dist/services/removeNonNumeric.js +16 -0
  61. package/dist/services/truncateLargeFields.d.ts +30 -1
  62. package/dist/services/truncateLargeFields.d.ts.map +1 -1
  63. package/dist/services/truncateLargeFields.js +34 -6
  64. package/dist/validations/validateCpf.d.ts +24 -0
  65. package/dist/validations/validateCpf.d.ts.map +1 -0
  66. package/dist/validations/validateCpf.js +56 -0
  67. package/dist/validations/validateDate.d.ts +27 -6
  68. package/dist/validations/validateDate.d.ts.map +1 -1
  69. package/dist/validations/validateDate.js +32 -6
  70. package/dist/validations/validatePhone.d.ts +27 -1
  71. package/dist/validations/validatePhone.d.ts.map +1 -1
  72. package/dist/validations/validatePhone.js +27 -2
  73. package/package.json +4 -2
  74. package/src/formats/formatDate.ts +97 -0
  75. package/src/formats/formatJsonObject.ts +68 -26
  76. package/src/formats/formatJsonString.ts +40 -4
  77. package/src/formats/formatToCep.ts +35 -7
  78. package/src/formats/formatToCnpj.ts +39 -0
  79. package/src/formats/formatToCpf.ts +39 -0
  80. package/src/formats/formatToCpfCnpj.ts +31 -7
  81. package/src/formats/formatToCurrency.ts +53 -0
  82. package/src/formats/formatToEllipsis.ts +23 -3
  83. package/src/formats/formatToHiddenDigits.ts +75 -7
  84. package/src/formats/formatToPhone.ts +156 -6
  85. package/src/generators/generateColorByString.ts +18 -4
  86. package/src/generators/generateId.ts +36 -5
  87. package/src/generators/generateSlug.ts +17 -2
  88. package/src/index.ts +7 -15
  89. package/src/regex/index.ts +8 -0
  90. package/src/services/calculateCardInstallment.ts +57 -12
  91. package/src/services/maskSensitiveData.ts +29 -4
  92. package/src/services/removeCurrencySymbols.ts +25 -0
  93. package/src/services/removeNonNumeric.ts +18 -0
  94. package/src/services/truncateLargeFields.ts +40 -6
  95. package/src/validations/validateCpf.ts +64 -0
  96. package/src/validations/validateDate.ts +33 -11
  97. package/src/validations/validatePhone.ts +29 -2
  98. package/tsconfig.json +1 -1
  99. package/vitest.config.ts +5 -0
  100. package/dist/formats/formatBrazilianDateHour.d.ts +0 -3
  101. package/dist/formats/formatBrazilianDateHour.d.ts.map +0 -1
  102. package/dist/formats/formatBrazilianDateHour.js +0 -12
  103. package/dist/formats/formatBrazilianDateToDate.d.ts +0 -3
  104. package/dist/formats/formatBrazilianDateToDate.d.ts.map +0 -1
  105. package/dist/formats/formatBrazilianDateToDate.js +0 -9
  106. package/dist/formats/formatDateHour.d.ts +0 -3
  107. package/dist/formats/formatDateHour.d.ts.map +0 -1
  108. package/dist/formats/formatDateHour.js +0 -11
  109. package/dist/formats/formatToBRL.d.ts +0 -3
  110. package/dist/formats/formatToBRL.d.ts.map +0 -1
  111. package/dist/formats/formatToBRL.js +0 -8
  112. package/dist/formats/formatToCNPJ.d.ts +0 -3
  113. package/dist/formats/formatToCNPJ.d.ts.map +0 -1
  114. package/dist/formats/formatToCNPJ.js +0 -9
  115. package/dist/formats/formatToCPF.d.ts +0 -3
  116. package/dist/formats/formatToCPF.d.ts.map +0 -1
  117. package/dist/formats/formatToCPF.js +0 -9
  118. package/dist/parsers/parseToCharacters.d.ts +0 -17
  119. package/dist/parsers/parseToCharacters.d.ts.map +0 -1
  120. package/dist/parsers/parseToCharacters.js +0 -13
  121. package/dist/services/range.d.ts +0 -4
  122. package/dist/services/range.d.ts.map +0 -1
  123. package/dist/services/range.js +0 -9
  124. package/dist/validations/regex.d.ts +0 -15
  125. package/dist/validations/regex.d.ts.map +0 -1
  126. package/dist/validations/regex.js +0 -25
  127. package/dist/validations/validateCPF.d.ts +0 -3
  128. package/dist/validations/validateCPF.d.ts.map +0 -1
  129. package/dist/validations/validateCPF.js +0 -36
  130. package/src/formats/formatBrazilianDateHour.ts +0 -17
  131. package/src/formats/formatBrazilianDateToDate.ts +0 -13
  132. package/src/formats/formatDateHour.ts +0 -15
  133. package/src/formats/formatToBRL.ts +0 -10
  134. package/src/formats/formatToCNPJ.ts +0 -10
  135. package/src/formats/formatToCPF.ts +0 -10
  136. package/src/parsers/parseToCharacters.ts +0 -34
  137. package/src/services/range.ts +0 -15
  138. package/src/validations/regex.ts +0 -41
  139. package/src/validations/validateCPF.ts +0 -38
@@ -1,3 +1,29 @@
1
- declare function validatePhone(phone: string): boolean;
1
+ import type { ValidatePhoneFunction } from "@arkyn/types";
2
+ /**
3
+ * Validates a phone number against a list of country-specific formats.
4
+ *
5
+ * The function iterates through a predefined list of countries and checks if the
6
+ * provided phone number matches the format for any of the countries. It uses
7
+ * regular expressions to validate the phone number based on the country's code,
8
+ * prefix, and mask.
9
+ *
10
+ * Special handling is applied for Brazilian phone numbers (ISO code "BR"), which
11
+ * allows for an optional ninth digit.
12
+ *
13
+ * @param phone - The phone number to validate as a string.
14
+ * @returns `true` if the phone number matches any country's format, otherwise `false`.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { validatePhone } from "./validatePhone";
19
+ *
20
+ * validatePhone("+55 32912345678"); // true for a valid Brazilian phone number
21
+ * validatePhone("+55 3212345678"); // true for a valid Brazilian phone number
22
+ * validatePhone("+1-684 1234567"); // true for a valid American Samoa phone number
23
+ * validatePhone("+5532912345678"); // false for an invalid Brazilian phone number
24
+ * validatePhone("+55 1234567890"); // false for an invalid Brazilian phone number
25
+ * ```
26
+ */
27
+ declare const validatePhone: ValidatePhoneFunction;
2
28
  export { validatePhone };
3
29
  //# sourceMappingURL=validatePhone.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validatePhone.d.ts","sourceRoot":"","sources":["../../src/validations/validatePhone.ts"],"names":[],"mappings":"AAEA,iBAAS,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAiB7C;AAED,OAAO,EAAE,aAAa,EAAE,CAAC"}
1
+ {"version":3,"file":"validatePhone.d.ts","sourceRoot":"","sources":["../../src/validations/validatePhone.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,QAAA,MAAM,aAAa,EAAE,qBAiBpB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC"}
@@ -1,5 +1,30 @@
1
1
  import { countries } from "@arkyn/templates";
2
- function validatePhone(phone) {
2
+ /**
3
+ * Validates a phone number against a list of country-specific formats.
4
+ *
5
+ * The function iterates through a predefined list of countries and checks if the
6
+ * provided phone number matches the format for any of the countries. It uses
7
+ * regular expressions to validate the phone number based on the country's code,
8
+ * prefix, and mask.
9
+ *
10
+ * Special handling is applied for Brazilian phone numbers (ISO code "BR"), which
11
+ * allows for an optional ninth digit.
12
+ *
13
+ * @param phone - The phone number to validate as a string.
14
+ * @returns `true` if the phone number matches any country's format, otherwise `false`.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { validatePhone } from "./validatePhone";
19
+ *
20
+ * validatePhone("+55 32912345678"); // true for a valid Brazilian phone number
21
+ * validatePhone("+55 3212345678"); // true for a valid Brazilian phone number
22
+ * validatePhone("+1-684 1234567"); // true for a valid American Samoa phone number
23
+ * validatePhone("+5532912345678"); // false for an invalid Brazilian phone number
24
+ * validatePhone("+55 1234567890"); // false for an invalid Brazilian phone number
25
+ * ```
26
+ */
27
+ const validatePhone = (phone) => {
3
28
  for (const country of countries) {
4
29
  const countryCode = country.code;
5
30
  const prefix = country.prefix ? `-${country.prefix}` : "";
@@ -15,5 +40,5 @@ function validatePhone(phone) {
15
40
  return true;
16
41
  }
17
42
  return false;
18
- }
43
+ };
19
44
  export { validatePhone };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arkyn/shared",
3
- "version": "1.4.52",
3
+ "version": "1.4.55",
4
4
  "main": "./dist/bundle.js",
5
5
  "module": "./src/index.ts",
6
6
  "type": "module",
@@ -8,10 +8,12 @@
8
8
  "scripts": {
9
9
  "clean": "rm -rf dist",
10
10
  "build": "bun run clean && bunx tsc --project tsconfig.json",
11
+ "test": "vitest --config ./vitest.config.ts",
11
12
  "typecheck": "bunx tsc --project tsconfig.json --noEmit"
12
13
  },
13
14
  "dependencies": {
14
- "uuid": "^10.0.0"
15
+ "uuid": "^10.0.0",
16
+ "vitest": "^3.1.1"
15
17
  },
16
18
  "devDependencies": {
17
19
  "@types/uuid": "^10.0.0",
@@ -0,0 +1,97 @@
1
+ import type { FormatDateFunction } from "@arkyn/types";
2
+
3
+ function formatDateString(date: Date, format: string): string {
4
+ const pad = (num: number) => num.toString().padStart(2, "0");
5
+
6
+ const replacements: Record<string, string> = {
7
+ YYYY: date.getFullYear().toString(),
8
+ YY: date.getFullYear().toString().slice(-2),
9
+ MM: pad(date.getMonth() + 1),
10
+ DD: pad(date.getDate()),
11
+ hh: pad(date.getHours()),
12
+ mm: pad(date.getMinutes()),
13
+ ss: pad(date.getSeconds()),
14
+ };
15
+
16
+ return format.replace(
17
+ /YYYY|YY|MM|DD|hh|mm|ss/g,
18
+ (match) => replacements[match]
19
+ );
20
+ }
21
+
22
+ /**
23
+ * Formats a date string from a given input format to a specified output format,
24
+ * with optional timezone adjustment.
25
+ *
26
+ * @param date - The date string to be formatted. It should match the specified `inputFormat`.
27
+ * @param time - The time string in the format `hh:mm:ss` (e.g., `14:30:00`).
28
+ * @param inputFormat - The format of the input date string. Supported formats:
29
+ * - `"brazilianDate"`: Expects the date in `DD/MM/YYYY` format.
30
+ * - `"isoDate"`: Expects the date in `YYYY-MM-DD` format.
31
+ * - `"timestamp"`: Expects the date as a numeric timestamp (e.g., `YYYY-MM-DD`).
32
+ *
33
+ * @param outputFormat - The desired format for the output date string. Supported tokens:
34
+ * - `YYYY`: Full year (e.g., 2023)
35
+ * - `YY`: Last two digits of the year (e.g., 23)
36
+ * - `MM`: Month (zero-padded, e.g., 01)
37
+ * - `DD`: Day of the month (zero-padded, e.g., 09)
38
+ * - `hh`: Hours (zero-padded, 24-hour format, e.g., 08)
39
+ * - `mm`: Minutes (zero-padded, e.g., 05)
40
+ * - `ss`: Seconds (zero-padded, e.g., 07)
41
+ * @param timezone - (Optional) The timezone offset in hours to adjust the date. Defaults to `0`.
42
+ *
43
+ * @returns The formatted date string in the specified `outputFormat`.
44
+ *
45
+ * @throws Will throw an error if:
46
+ * - The `inputFormat` is invalid.
47
+ * - The `date` string does not match the expected `inputFormat`.
48
+ * - The `time` string is not in the format `hh:mm:ss`.
49
+ * - The resulting date is invalid.
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * import { formatDate } from "./formatDate";
54
+ *
55
+ * const date = "25/12/2023";
56
+ * const time = "14:30:00";
57
+ * const formatted = formatDate(date, time, "brazilianDate", "YYYY-MM-DD hh:mm:ss", -3);
58
+ * console.log(formatted); // Outputs: "2023-12-25 14:30:00"
59
+ * ```
60
+ */
61
+
62
+ const formatDate: FormatDateFunction = (
63
+ date,
64
+ time,
65
+ inputFormat,
66
+ outputFormat,
67
+ timezone = 0
68
+ ) => {
69
+ const dateParts = date.split(/[-/]/).map(Number);
70
+ const timeParts = time.split(":").map(Number);
71
+
72
+ let day, month, year;
73
+ const [hours = 0, minutes = 0, seconds = 0] = timeParts;
74
+
75
+ switch (inputFormat) {
76
+ case "brazilianDate":
77
+ [day, month, year] = dateParts;
78
+ break;
79
+ case "isoDate":
80
+ [year, month, day] = dateParts;
81
+ break;
82
+ case "timestamp":
83
+ [year, month, day] = dateParts.map(Number);
84
+ break;
85
+ default:
86
+ throw new Error("Invalid input format");
87
+ }
88
+
89
+ const formattedDate = new Date(year, month - 1, day, hours, minutes, seconds);
90
+ if (isNaN(formattedDate.getTime())) throw new Error("Invalid date");
91
+
92
+ formattedDate.setUTCHours(formattedDate.getUTCHours() + timezone);
93
+
94
+ return formatDateString(formattedDate, outputFormat);
95
+ };
96
+
97
+ export { formatDate };
@@ -1,35 +1,77 @@
1
- function formatJsonObject(obj: any, indentLevel: number): string {
1
+ import type { FormatJsonObjectFunction } from "@arkyn/types";
2
+
3
+ /**
4
+ * Formats a JSON object into a human-readable string with proper indentation.
5
+ *
6
+ * @param obj - The JSON object or value to format. It can be an object, array, string, or primitive value.
7
+ * @param indentLevel - The current level of indentation to apply. This is used recursively to format nested structures.
8
+ * @returns A formatted string representation of the JSON object.
9
+ *
10
+ * @remarks
11
+ * - If the input is an object, it will be formatted with keys and values properly indented.
12
+ * - If the input is an array, each element will be formatted and indented on a new line.
13
+ * - If the input is a string that can be parsed as JSON, it will attempt to parse and format it.
14
+ * - Primitive values (e.g., numbers, booleans, null) will be converted to their string representation.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const obj = { name: "John", age: 30, hobbies: ["reading", "gaming"] };
19
+ * const formatted = formatJsonObject(obj, 0);
20
+ * console.log(formatted);
21
+ * // Output:
22
+ * // {
23
+ * // "name": "John",
24
+ * // "age": 30,
25
+ * // "hobbies": [
26
+ * // "reading",
27
+ * // "gaming"
28
+ * // ]
29
+ * // }
30
+ * ```
31
+ */
32
+
33
+ const formatJsonObject: FormatJsonObjectFunction = (obj, indentLevel) => {
2
34
  const indent = " ".repeat(indentLevel);
3
35
  let formattedString = "";
4
36
 
5
37
  if (typeof obj === "object" && obj !== null) {
6
38
  if (Array.isArray(obj)) {
7
- formattedString += "[\n";
8
- obj.forEach((item, index) => {
9
- formattedString +=
10
- indent + " " + formatJsonObject(item, indentLevel + 1);
11
- if (index < obj.length - 1) {
12
- formattedString += ",";
13
- }
14
- formattedString += "\n";
15
- });
16
- formattedString += indent + "]";
39
+ if (obj.length === 0) {
40
+ // Caso especial para arrays vazios
41
+ formattedString += "[]";
42
+ } else {
43
+ formattedString += "[\n";
44
+ obj.forEach((item, index) => {
45
+ formattedString +=
46
+ indent + " " + formatJsonObject(item, indentLevel + 1);
47
+ if (index < obj.length - 1) {
48
+ formattedString += ",";
49
+ }
50
+ formattedString += "\n";
51
+ });
52
+ formattedString += indent + "]";
53
+ }
17
54
  } else {
18
- formattedString += "{\n";
19
55
  const keys = Object.keys(obj);
20
- keys.forEach((key, index) => {
21
- formattedString +=
22
- indent +
23
- ' "' +
24
- key +
25
- '": ' +
26
- formatJsonObject(obj[key], indentLevel + 1);
27
- if (index < keys.length - 1) {
28
- formattedString += ",";
29
- }
30
- formattedString += "\n";
31
- });
32
- formattedString += indent + "}";
56
+ if (keys.length === 0) {
57
+ // Caso especial para objetos vazios
58
+ formattedString += "{}";
59
+ } else {
60
+ formattedString += "{\n";
61
+ keys.forEach((key, index) => {
62
+ formattedString +=
63
+ indent +
64
+ ' "' +
65
+ key +
66
+ '": ' +
67
+ formatJsonObject(obj[key], indentLevel + 1);
68
+ if (index < keys.length - 1) {
69
+ formattedString += ",";
70
+ }
71
+ formattedString += "\n";
72
+ });
73
+ formattedString += indent + "}";
74
+ }
33
75
  }
34
76
  } else if (typeof obj === "string") {
35
77
  try {
@@ -43,6 +85,6 @@ function formatJsonObject(obj: any, indentLevel: number): string {
43
85
  }
44
86
 
45
87
  return formattedString;
46
- }
88
+ };
47
89
 
48
90
  export { formatJsonObject };
@@ -1,13 +1,49 @@
1
+ import type { FormatJsonStringFunction } from "@arkyn/types";
1
2
  import { formatJsonObject } from "./formatJsonObject";
2
3
 
3
- function formatJsonString(jsonString: string): string {
4
+ /**
5
+ * Formats a JSON string into a more readable format.
6
+ *
7
+ * This function attempts to parse the provided JSON string into a JavaScript object,
8
+ * and then formats it using the `formatJsonObject` function. If the input string
9
+ * is not a valid JSON, it logs an error to the console and returns an empty string.
10
+ *
11
+ * @param jsonString - The JSON string to be formatted.
12
+ * @returns A formatted JSON string, or an empty string if the input is invalid.
13
+ *
14
+ * @throws Will log an error to the console if the input is not a valid JSON string.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const jsonString = '{"name":"John","age":30,"hobbies":["reading","gaming"]}';
19
+ * const formatted = formatJsonString(jsonString);
20
+ * console.log(formatted);
21
+ * // Output:
22
+ * // {
23
+ * // "name": "John",
24
+ * // "age": 30,
25
+ * // "hobbies": [
26
+ * // "reading",
27
+ * // "gaming"
28
+ * // ]
29
+ * // }
30
+
31
+ * const invalidJsonString = '{"name":"John", "age":30,';
32
+ * const formatted = formatJsonString(invalidJsonString);
33
+ * console.log(formatted);
34
+ * // Output:
35
+ * // (Logs "Invalid JSON string: ..." to the console)
36
+ * // ""
37
+ * ```
38
+ */
39
+
40
+ const formatJsonString: FormatJsonStringFunction = (jsonString) => {
4
41
  try {
5
42
  const jsonObject = JSON.parse(jsonString);
6
43
  return formatJsonObject(jsonObject, 0);
7
44
  } catch (error) {
8
- console.error("Invalid JSON string:", error);
9
- return "";
45
+ throw new Error(`Invalid JSON string \n ${error}`);
10
46
  }
11
- }
47
+ };
12
48
 
13
49
  export { formatJsonString };
@@ -1,10 +1,38 @@
1
- function formatToCep(value: string): string {
2
- const cleaned = value.replace(/\D/g, "");
1
+ import type { FormatToCepFunction } from "@arkyn/types";
2
+ import { removeNonNumeric } from "../services/removeNonNumeric";
3
+
4
+ /**
5
+ * Formats a given string into a Brazilian postal code (CEP) format.
6
+ *
7
+ * The function removes all non-numeric characters from the input string
8
+ * and attempts to format it as a CEP in the pattern `XXXXX-XXX`.
9
+ * If the input does not match the expected format, an error is thrown.
10
+ *
11
+ * @param value - The input string to be formatted as a CEP.
12
+ * @returns The formatted CEP string in the pattern `XXXXX-XXX`.
13
+ * @throws {Error} If the input does not match the expected CEP format.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * import { formatToCep } from "./formatToCep";
18
+ *
19
+ * const formattedCep = formatToCep("12345678");
20
+ * console.log(formattedCep); // Output: "12345-678"
21
+ *
22
+ * try {
23
+ * formatToCep("1234");
24
+ * } catch (error) {
25
+ * console.error(error.message); // Output: "Invalid CEP format"
26
+ * }
27
+ * ```
28
+ */
29
+
30
+ const formatToCep: FormatToCepFunction = (value) => {
31
+ const cleaned = removeNonNumeric(value);
3
32
  const match = cleaned.match(/^(\d{5})(\d{3})$/);
4
- if (match) {
5
- return `${match[1]}-${match[2]}`;
6
- }
7
- return value;
8
- }
33
+
34
+ if (match) return `${match[1]}-${match[2]}`;
35
+ throw new Error("Invalid CEP format");
36
+ };
9
37
 
10
38
  export { formatToCep };
@@ -0,0 +1,39 @@
1
+ import type { FormatToCnpjFunction } from "@arkyn/types";
2
+ import { removeNonNumeric } from "../services/removeNonNumeric";
3
+
4
+ /**
5
+ * Formats a given string or number into a CNPJ (Cadastro Nacional da Pessoa Jurídica) format.
6
+ *
7
+ * The CNPJ format is: `XX.XXX.XXX/XXXX-XX`, where `X` represents a digit.
8
+ *
9
+ * @param value - The input value to be formatted. It can be a string or number containing the CNPJ digits.
10
+ * Non-numeric characters will be removed before formatting.
11
+ *
12
+ * @returns A string formatted as a CNPJ.
13
+ *
14
+ * @throws {Error} Throws an error if the input does not contain exactly 14 numeric digits.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { formatToCnpj } from "./formatToCNPJ";
19
+ *
20
+ * const formattedCnpj = formatToCnpj("12345678000195");
21
+ * console.log(formattedCnpj); // Output: "12.345.678/0001-95"
22
+ *
23
+ * try {
24
+ * formatToCnpj("12345");
25
+ * } catch (error) {
26
+ * console.error(error.message); // Output: "Invalid CNPJ length"
27
+ * }
28
+ * ```
29
+ */
30
+
31
+ const formatToCnpj: FormatToCnpjFunction = (value) => {
32
+ const cleaned = removeNonNumeric(value);
33
+ const match = cleaned.match(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/);
34
+ if (match)
35
+ return `${match[1]}.${match[2]}.${match[3]}/${match[4]}-${match[5]}`;
36
+ throw new Error("Invalid CNPJ length");
37
+ };
38
+
39
+ export { formatToCnpj };
@@ -0,0 +1,39 @@
1
+ import type { FormatToCpfFunction } from "@arkyn/types";
2
+ import { removeNonNumeric } from "../services/removeNonNumeric";
3
+
4
+ /**
5
+ * Formats a given string into a CPF (Cadastro de Pessoas Físicas) format.
6
+ *
7
+ * A CPF is a Brazilian individual taxpayer registry identification format.
8
+ * This function ensures the input is cleaned of non-numeric characters and
9
+ * then formats it into the standard CPF format: `XXX.XXX.XXX-XX`.
10
+ *
11
+ * @param value - The input string to be formatted as a CPF.
12
+ * @returns The formatted CPF string.
13
+ * @throws {Error} If the input string does not match the expected CPF format.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * import { formatToCpf } from "./formatToCPF";
18
+ *
19
+ * const formattedCpf = formatToCpf("12345678909");
20
+ * console.log(formattedCpf); // Output: "123.456.789-09"
21
+
22
+ * try {
23
+ * const formattedCpf = formatToCpf("12345");
24
+ * } catch (error) {
25
+ * console.error(error.message); // Output: "Invalid CPF format"
26
+ * }
27
+ *
28
+ * ```
29
+ */
30
+
31
+ const formatToCpf: FormatToCpfFunction = (value) => {
32
+ const cleaned = removeNonNumeric(value);
33
+ const match = cleaned.match(/^(\d{3})(\d{3})(\d{3})(\d{2})$/);
34
+
35
+ if (match) return `${match[1]}.${match[2]}.${match[3]}-${match[4]}`;
36
+ throw new Error("Invalid CPF format");
37
+ };
38
+
39
+ export { formatToCpf };
@@ -1,14 +1,38 @@
1
- import { formatToCNPJ } from "./formatToCNPJ";
2
- import { formatToCPF } from "./formatToCPF";
1
+ import type { FormatToCpfCnpjFunction } from "@arkyn/types";
3
2
 
4
- function formatToCpfCnpj(value: string): string {
3
+ import { formatToCnpj } from "./formatToCnpj";
4
+ import { formatToCpf } from "./formatToCpf";
5
+
6
+ /**
7
+ * Formats a given string value into either a CPF or CNPJ format based on its length.
8
+ *
9
+ * - If the input contains 11 numeric characters, it is formatted as a CPF.
10
+ * - If the input contains 14 numeric characters, it is formatted as a CNPJ.
11
+ * - Throws an error if the input length is neither 11 nor 14 after removing non-numeric characters.
12
+ *
13
+ * @param value - The string value to be formatted. It may contain non-numeric characters, which will be removed.
14
+ * @returns The formatted CPF or CNPJ string.
15
+ * @throws {Error} If the input does not have a valid CPF or CNPJ length.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * formatToCpfCnpj("123.456.789-09"); // Returns "123.456.789-09" (CPF format)
20
+ * formatToCpfCnpj("12.345.678/0001-95"); // Returns "12.345.678/0001-95" (CNPJ format)
21
+ * formatToCpfCnpj("12345678909"); // Returns "123.456.789-09" (CPF format)
22
+ * formatToCpfCnpj("12345678000195"); // Returns "12.345.678/0001-95" (CNPJ format)
23
+ * formatToCpfCnpj("123"); // Throws an error: "Invalid CPF or CNPJ length"
24
+ * ```
25
+ */
26
+
27
+ const formatToCpfCnpj: FormatToCpfCnpjFunction = (value) => {
5
28
  const cleaned = value.replace(/\D/g, "");
6
29
  if (cleaned.length === 11) {
7
- return formatToCPF(cleaned);
30
+ return formatToCpf(cleaned);
8
31
  } else if (cleaned.length === 14) {
9
- return formatToCNPJ(cleaned);
32
+ return formatToCnpj(cleaned);
10
33
  }
11
- return value;
12
- }
34
+
35
+ throw new Error("Invalid CPF or CNPJ length");
36
+ };
13
37
 
14
38
  export { formatToCpfCnpj };
@@ -0,0 +1,53 @@
1
+ import { countryCurrencies } from "@arkyn/templates";
2
+ import type { FormatToCurrency } from "@arkyn/types";
3
+
4
+ import { removeCurrencySymbols } from "../services/removeCurrencySymbols";
5
+
6
+ /**
7
+ * Formats a numeric value into a currency string based on the specified currency and configuration.
8
+ *
9
+ * @param value - The numeric value to be formatted.
10
+ * @param currency - The currency code used to determine the formatting style.
11
+ * @param config - Optional configuration object.
12
+ * @param config.showPrefix - Determines whether the currency symbol/prefix should be included in the formatted string. Defaults to `true`.
13
+ *
14
+ * @returns A formatted currency string. If `config.showPrefix` is `false`, the currency symbol is removed.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const formatted = formatToCurrency(1234.56, "USD", { showPrefix: true });
19
+ * console.log(formatted); // "$1,234.56"
20
+ *
21
+ * const withoutPrefix = formatToCurrency(1234.56, "USD", { showPrefix: false });
22
+ * console.log(withoutPrefix); // "1,234.56"
23
+ *
24
+ * const formattedBRL = formatToCurrency(1234.56, "BRL", { showPrefix: true });
25
+ * console.log(formattedBRL); // "R$ 1.234,56"
26
+ *
27
+ * const withoutPrefixBRL = formatToCurrency(1234.56, "BRL", { showPrefix: false });
28
+ * console.log(withoutPrefixBRL); // "1.234,56"
29
+ * ```
30
+ */
31
+
32
+ const formatToCurrency: FormatToCurrency = (
33
+ value,
34
+ currency,
35
+ config = { showPrefix: true }
36
+ ) => {
37
+ if (!countryCurrencies[currency]) {
38
+ throw new Error("Unsupported currency code");
39
+ }
40
+
41
+ const { countryCurrency, countryLanguage } = countryCurrencies[currency];
42
+
43
+ const format = new Intl.NumberFormat(countryLanguage, {
44
+ style: "currency",
45
+ currency: countryCurrency,
46
+ }).format(value);
47
+
48
+ return config.showPrefix
49
+ ? format.replace(/\s/g, " ")
50
+ : removeCurrencySymbols(format).replace(/\s/g, " ");
51
+ };
52
+
53
+ export { formatToCurrency };
@@ -1,5 +1,25 @@
1
- function formatToEllipsis(text: string, size = 40): string {
2
- return text.length > size ? `${text.substring(0, size)}...` : text;
3
- }
1
+ import type { FormatToEllipsisFunction } from "@arkyn/types";
2
+
3
+ /**
4
+ * Truncates a given text to a specified maximum length and appends an ellipsis ("...")
5
+ * if the text exceeds the maximum length.
6
+ *
7
+ * @param text - The input string to be truncated.
8
+ * @param maxLength - The maximum allowed length of the string before truncation.
9
+ * @returns The truncated string with an ellipsis if the input exceeds the maximum length,
10
+ * or the original string if it does not.
11
+ * @example
12
+ * const result = formatToEllipsis("Hello, world!", 5);
13
+ * console.log(result); // Output: "Hello..."
14
+ */
15
+
16
+ const formatToEllipsis: FormatToEllipsisFunction = (text, maxLength) => {
17
+ if (text.length > maxLength) {
18
+ let trimmedText = text.substring(0, maxLength).trimEnd();
19
+ trimmedText = trimmedText.replace(/[.,!?;:]$/, "");
20
+ return `${trimmedText}...`;
21
+ }
22
+ return text;
23
+ };
4
24
 
5
25
  export { formatToEllipsis };