@atlantjs/arch 13.2.0 → 14.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/@tool-box/utils/convert-units/convert-units.d.ts +14 -5
- package/@tool-box/utils/convert-units/convert-units.js +100 -8
- package/@tool-box/utils/datatypes/boolean-utils.d.ts +7 -0
- package/@tool-box/utils/datatypes/boolean-utils.js +146 -4
- package/@tool-box/utils/datatypes/string-utils.d.ts +20 -4
- package/@tool-box/utils/datatypes/string-utils.js +300 -14
- package/@tool-box/utils/ducts/common.d.ts +49 -0
- package/@tool-box/utils/ducts/common.js +36 -3
- package/@tool-box/utils/ducts/optional-type.d.ts +85 -0
- package/@tool-box/utils/ducts/optional-type.js +79 -0
- package/@tool-box/utils/ducts/return-type.d.ts +17 -17
- package/@tool-box/utils/ducts/return-type.js +14 -4
- package/@tool-box/utils/http-provider/http-provider.d.ts +6 -0
- package/@tool-box/utils/http-provider/http-provider.js +43 -14
- package/@tool-box/utils/map/map.abstract.d.ts +39 -0
- package/@tool-box/utils/map/map.abstract.js +70 -6
- package/@tool-box/utils/random/random.d.ts +168 -0
- package/@tool-box/utils/random/random.js +235 -0
- package/@tool-box/utils/type-guard/guardian.d.ts +450 -7
- package/@tool-box/utils/type-guard/guardian.js +539 -35
- package/objects/@common/edges/cron-expression.edge.d.ts +30 -2
- package/objects/@common/edges/cron-expression.edge.js +77 -5
- package/objects/@common/edges/email.edge.d.ts +39 -1
- package/objects/@common/edges/email.edge.js +80 -2
- package/objects/@common/edges/ulid.sketch.edge.d.ts +48 -1
- package/objects/@common/edges/ulid.sketch.edge.js +75 -4
- package/objects/@common/edges/url.edge.d.ts +182 -0
- package/objects/@common/edges/url.edge.js +249 -0
- package/objects/@common/edges/username.edge.d.ts +9 -0
- package/objects/@common/edges/username.edge.js +34 -0
- package/objects/@common/edges/uuid.sketch.edge.d.ts +97 -1
- package/objects/@common/edges/uuid.sketch.edge.js +127 -6
- package/objects/amount/amount-value.edge.d.ts +42 -0
- package/objects/amount/amount-value.edge.js +76 -0
- package/objects/amount/amount.edge.d.ts +389 -11
- package/objects/amount/amount.edge.js +543 -4
- package/objects/datetime/edges/datetime.edge.d.ts +422 -4
- package/objects/datetime/edges/datetime.edge.js +538 -33
- package/objects/password/password.edge.d.ts +90 -0
- package/objects/password/password.edge.js +140 -6
- package/objects/primitives/boolean.edge.sketch.d.ts +105 -3
- package/objects/primitives/boolean.edge.sketch.js +132 -6
- package/objects/primitives/number.edge.sketch.d.ts +236 -0
- package/objects/primitives/number.edge.sketch.js +310 -24
- package/objects/primitives/string.edge.sketch.d.ts +148 -0
- package/objects/primitives/string.edge.sketch.js +191 -7
- package/objects/schedule/schedule.edge.d.ts +194 -0
- package/objects/schedule/schedule.edge.js +269 -2
- package/objects/time/time.edge.d.ts +285 -2
- package/objects/time/time.edge.js +385 -6
- package/package.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,38 +1,324 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
// ==================== Transformação de Casing ====================
|
|
3
|
+
/**
|
|
4
|
+
* Converte a string para o formato kebab-case.
|
|
5
|
+
* Separa palavras com hífen e converte tudo para minúsculas.
|
|
6
|
+
* @returns String no formato kebab-case
|
|
7
|
+
* @example
|
|
8
|
+
* "helloWorld".toKebabCase() // "hello-world"
|
|
9
|
+
* "FooBarBaz".toKebabCase() // "foo-bar-baz"
|
|
10
|
+
*/
|
|
2
11
|
String.prototype.toKebabCase = function () {
|
|
3
12
|
return this.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
|
4
13
|
};
|
|
14
|
+
/**
|
|
15
|
+
* Converte a string para o formato snake_case.
|
|
16
|
+
* Separa palavras com underscore e converte tudo para minúsculas.
|
|
17
|
+
* @returns String no formato snake_case
|
|
18
|
+
* @example
|
|
19
|
+
* "helloWorld".toSnakeCase() // "hello_world"
|
|
20
|
+
* "FooBarBaz".toSnakeCase() // "foo_bar_baz"
|
|
21
|
+
*/
|
|
5
22
|
String.prototype.toSnakeCase = function () {
|
|
6
23
|
return this.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
|
|
7
24
|
};
|
|
25
|
+
/**
|
|
26
|
+
* Converte a string para o formato camelCase.
|
|
27
|
+
* Remove espaços e capitaliza a primeira letra de cada palavra, exceto a primeira.
|
|
28
|
+
* @returns String no formato camelCase
|
|
29
|
+
* @example
|
|
30
|
+
* "hello world".toCamelCase() // "helloWorld"
|
|
31
|
+
* "foo bar baz".toCamelCase() // "fooBarBaz"
|
|
32
|
+
*/
|
|
33
|
+
String.prototype.toCamelCase = function () {
|
|
34
|
+
return this.valueOf()
|
|
35
|
+
.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match, index) => index === 0 ? match.toLowerCase() : match.toUpperCase())
|
|
36
|
+
.replace(/\s+/g, "");
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Converte a string para o formato PascalCase.
|
|
40
|
+
* Remove espaços e capitaliza a primeira letra de cada palavra.
|
|
41
|
+
* @returns String no formato PascalCase
|
|
42
|
+
* @example
|
|
43
|
+
* "hello world".toPascalCase() // "HelloWorld"
|
|
44
|
+
* "foo bar baz".toPascalCase() // "FooBarBaz"
|
|
45
|
+
*/
|
|
8
46
|
String.prototype.toPascalCase = function () {
|
|
9
|
-
return this.
|
|
47
|
+
return this.valueOf()
|
|
48
|
+
.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match) => match.toUpperCase())
|
|
49
|
+
.replace(/\s+/g, "");
|
|
10
50
|
};
|
|
11
|
-
|
|
12
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Converte a string para o formato Title Case.
|
|
53
|
+
* Capitaliza a primeira letra de cada palavra, mantendo as demais em minúsculo.
|
|
54
|
+
* @returns String no formato Title Case
|
|
55
|
+
* @example
|
|
56
|
+
* "hello world".toTitleCase() // "Hello World"
|
|
57
|
+
* "the quick brown fox".toTitleCase() // "The Quick Brown Fox"
|
|
58
|
+
*/
|
|
59
|
+
String.prototype.toTitleCase = function () {
|
|
60
|
+
return this.valueOf()
|
|
61
|
+
.toLowerCase()
|
|
62
|
+
.replace(/(?:^|\s)\w/g, (match) => match.toUpperCase());
|
|
13
63
|
};
|
|
64
|
+
/**
|
|
65
|
+
* Capitaliza a primeira letra de cada palavra da string.
|
|
66
|
+
* @returns String com a primeira letra de cada palavra em maiúsculo
|
|
67
|
+
* @example
|
|
68
|
+
* "hello world".capitalize() // "Hello World"
|
|
69
|
+
* "foo BAR".capitalize() // "Foo Bar"
|
|
70
|
+
*/
|
|
14
71
|
String.prototype.capitalize = function () {
|
|
15
|
-
return this.
|
|
72
|
+
return this.valueOf()
|
|
73
|
+
.split(" ")
|
|
16
74
|
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
|
17
75
|
.join(" ");
|
|
18
76
|
};
|
|
19
|
-
|
|
20
|
-
|
|
77
|
+
// ==================== Manipulação ====================
|
|
78
|
+
/**
|
|
79
|
+
* Remove espaços extras e faz trim na string.
|
|
80
|
+
* Substitui múltiplos espaços consecutivos por um único espaço.
|
|
81
|
+
* @returns String sem espaços extras
|
|
82
|
+
* @example
|
|
83
|
+
* " hello world ".sanitize() // "hello world"
|
|
84
|
+
* "foo bar".sanitize() // "foo bar"
|
|
85
|
+
*/
|
|
86
|
+
String.prototype.sanitize = function () {
|
|
87
|
+
return this.valueOf().replace(/\s+/g, " ").trim();
|
|
21
88
|
};
|
|
89
|
+
/**
|
|
90
|
+
* Trunca a string para um comprimento máximo, adicionando "..." ao final.
|
|
91
|
+
* Se a string já for menor ou igual ao comprimento, retorna sem alteração.
|
|
92
|
+
* @param length - Comprimento máximo da string resultante (incluindo "...")
|
|
93
|
+
* @returns String truncada com "..." se necessário
|
|
94
|
+
* @example
|
|
95
|
+
* "Hello World".truncate(8) // "Hello..."
|
|
96
|
+
* "Hi".truncate(8) // "Hi"
|
|
97
|
+
*/
|
|
22
98
|
String.prototype.truncate = function (length) {
|
|
23
|
-
if (this.length <= length)
|
|
24
|
-
return this;
|
|
25
|
-
return `${this.substring(0, length - 3)}...`;
|
|
99
|
+
if (this.valueOf().length <= length)
|
|
100
|
+
return this.valueOf();
|
|
101
|
+
return `${this.valueOf().substring(0, length - 3)}...`;
|
|
26
102
|
};
|
|
103
|
+
/**
|
|
104
|
+
* Remove todos os espaços em branco da string.
|
|
105
|
+
* @returns String sem nenhum espaço em branco
|
|
106
|
+
* @example
|
|
107
|
+
* "hello world".removeWhitespace() // "helloworld"
|
|
108
|
+
* " foo bar ".removeWhitespace() // "foobar"
|
|
109
|
+
*/
|
|
27
110
|
String.prototype.removeWhitespace = function () {
|
|
28
|
-
return this.replace(/\s+/g, "");
|
|
111
|
+
return this.valueOf().replace(/\s+/g, "");
|
|
29
112
|
};
|
|
30
|
-
|
|
31
|
-
|
|
113
|
+
/**
|
|
114
|
+
* Inverte os caracteres da string.
|
|
115
|
+
* @returns String com os caracteres em ordem inversa
|
|
116
|
+
* @example
|
|
117
|
+
* "hello".reverse() // "olleh"
|
|
118
|
+
* "abcd".reverse() // "dcba"
|
|
119
|
+
*/
|
|
120
|
+
String.prototype.reverse = function () {
|
|
121
|
+
return this.valueOf().split("").reverse().join("");
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* Repete a string um número específico de vezes.
|
|
125
|
+
* @param times - Número de vezes que a string será repetida
|
|
126
|
+
* @returns String repetida o número de vezes especificado
|
|
127
|
+
* @example
|
|
128
|
+
* "ab".repeat(3) // "ababab"
|
|
129
|
+
* "ha".repeat(2) // "haha"
|
|
130
|
+
*/
|
|
131
|
+
String.prototype.repeat = function (times) {
|
|
132
|
+
return this.valueOf().repeat(times);
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* Preenche o início da string com um caractere até atingir o comprimento especificado.
|
|
136
|
+
* @param length - Comprimento total desejado da string
|
|
137
|
+
* @param char - Caractere de preenchimento (padrão: " ")
|
|
138
|
+
* @returns String preenchida à esquerda
|
|
139
|
+
* @example
|
|
140
|
+
* "5".padStart(3, "0") // "005"
|
|
141
|
+
* "hi".padStart(5) // " hi"
|
|
142
|
+
*/
|
|
143
|
+
String.prototype.padStart = function (length, char = " ") {
|
|
144
|
+
return this.valueOf().padStart(length, char);
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Preenche o final da string com um caractere até atingir o comprimento especificado.
|
|
148
|
+
* @param length - Comprimento total desejado da string
|
|
149
|
+
* @param char - Caractere de preenchimento (padrão: " ")
|
|
150
|
+
* @returns String preenchida à direita
|
|
151
|
+
* @example
|
|
152
|
+
* "5".padEnd(3, "0") // "500"
|
|
153
|
+
* "hi".padEnd(5) // "hi "
|
|
154
|
+
*/
|
|
155
|
+
String.prototype.padEnd = function (length, char = " ") {
|
|
156
|
+
return this.valueOf().padEnd(length, char);
|
|
157
|
+
};
|
|
158
|
+
function escapeRegExp(value) {
|
|
159
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Substitui todas as ocorrências de uma substring por outra.
|
|
163
|
+
* @param search - Substring/RegExp a ser substituída
|
|
164
|
+
* @param replacement - String de substituição ou função de substituição
|
|
165
|
+
* @returns Nova string com todas as ocorrências substituídas
|
|
166
|
+
* @example
|
|
167
|
+
* "foo bar foo".replaceAll("foo", "baz") // "baz bar baz"
|
|
168
|
+
*/
|
|
169
|
+
String.prototype.replaceAll = function (search, replacement) {
|
|
170
|
+
const source = this.valueOf();
|
|
171
|
+
if (search instanceof RegExp) {
|
|
172
|
+
const flags = search.flags.includes("g")
|
|
173
|
+
? search.flags
|
|
174
|
+
: `${search.flags}g`;
|
|
175
|
+
return source.replace(new RegExp(search.source, flags), replacement);
|
|
176
|
+
}
|
|
177
|
+
const literalGlobalRegex = new RegExp(escapeRegExp(search), "g");
|
|
178
|
+
return source.replace(literalGlobalRegex, replacement);
|
|
179
|
+
};
|
|
180
|
+
// ==================== Verificação de Conteúdo ====================
|
|
181
|
+
/**
|
|
182
|
+
* Verifica se a string contém uma substring específica.
|
|
183
|
+
* @param substring - Substring a ser procurada
|
|
184
|
+
* @returns true se a substring foi encontrada, false caso contrário
|
|
185
|
+
* @example
|
|
186
|
+
* "hello world".contains("world") // true
|
|
187
|
+
* "hello world".contains("foo") // false
|
|
188
|
+
*/
|
|
189
|
+
String.prototype.contains = function (substring) {
|
|
190
|
+
return this.valueOf().indexOf(substring) !== -1;
|
|
32
191
|
};
|
|
192
|
+
/**
|
|
193
|
+
* Verifica se a string começa com uma substring específica.
|
|
194
|
+
* @param substring - Substring a ser verificada no início
|
|
195
|
+
* @returns true se a string começa com a substring, false caso contrário
|
|
196
|
+
* @example
|
|
197
|
+
* "hello world".startsWith("hello") // true
|
|
198
|
+
* "hello world".startsWith("world") // false
|
|
199
|
+
*/
|
|
200
|
+
String.prototype.startsWith = function (substring) {
|
|
201
|
+
return this.valueOf().startsWith(substring);
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* Verifica se a string termina com uma substring específica.
|
|
205
|
+
* @param substring - Substring a ser verificada no final
|
|
206
|
+
* @returns true se a string termina com a substring, false caso contrário
|
|
207
|
+
* @example
|
|
208
|
+
* "hello world".endsWith("world") // true
|
|
209
|
+
* "hello world".endsWith("hello") // false
|
|
210
|
+
*/
|
|
211
|
+
String.prototype.endsWith = function (substring) {
|
|
212
|
+
return this.valueOf().endsWith(substring);
|
|
213
|
+
};
|
|
214
|
+
/**
|
|
215
|
+
* Conta o número de ocorrências de uma substring na string.
|
|
216
|
+
* @param substring - Substring a ser contada
|
|
217
|
+
* @returns Número de ocorrências encontradas
|
|
218
|
+
* @example
|
|
219
|
+
* "hello world hello".countOccurrences("hello") // 2
|
|
220
|
+
* "aaaa".countOccurrences("aa") // 2
|
|
221
|
+
*/
|
|
222
|
+
String.prototype.countOccurrences = function (substring) {
|
|
223
|
+
if (substring.length === 0)
|
|
224
|
+
return 0;
|
|
225
|
+
return this.valueOf().split(substring).length - 1;
|
|
226
|
+
};
|
|
227
|
+
// ==================== Validações ====================
|
|
228
|
+
/**
|
|
229
|
+
* Verifica se a string está vazia (sem nenhum caractere).
|
|
230
|
+
* @returns true se a string não possui caracteres, false caso contrário
|
|
231
|
+
* @example
|
|
232
|
+
* "".isEmpty() // true
|
|
233
|
+
* "hello".isEmpty() // false
|
|
234
|
+
*/
|
|
33
235
|
String.prototype.isEmpty = function () {
|
|
34
|
-
return this.length
|
|
236
|
+
return this.valueOf().length === 0;
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Verifica se a string possui conteúdo (não está vazia).
|
|
240
|
+
* @returns true se a string possui pelo menos um caractere, false caso contrário
|
|
241
|
+
* @example
|
|
242
|
+
* "hello".isFilled() // true
|
|
243
|
+
* "".isFilled() // false
|
|
244
|
+
*/
|
|
245
|
+
String.prototype.isFilled = function () {
|
|
246
|
+
return this.valueOf().length > 0;
|
|
247
|
+
};
|
|
248
|
+
/**
|
|
249
|
+
* Verifica se a string é um palíndromo (lida da mesma forma de frente para trás).
|
|
250
|
+
* @returns true se a string é um palíndromo, false caso contrário
|
|
251
|
+
* @example
|
|
252
|
+
* "racecar".isPalindrome() // true
|
|
253
|
+
* "hello".isPalindrome() // false
|
|
254
|
+
*/
|
|
255
|
+
String.prototype.isPalindrome = function () {
|
|
256
|
+
const clean = this.valueOf().toLowerCase().removeWhitespace();
|
|
257
|
+
return clean === clean.split("").reverse().join("");
|
|
258
|
+
};
|
|
259
|
+
/**
|
|
260
|
+
* Verifica se a string representa um valor numérico válido.
|
|
261
|
+
* @returns true se a string pode ser convertida para número, false caso contrário
|
|
262
|
+
* @example
|
|
263
|
+
* "42".isNumeric() // true
|
|
264
|
+
* "3.14".isNumeric() // true
|
|
265
|
+
* "hello".isNumeric() // false
|
|
266
|
+
*/
|
|
267
|
+
String.prototype.isNumeric = function () {
|
|
268
|
+
return !Number.isNaN(Number(this.valueOf())) && this.valueOf().isFilled();
|
|
269
|
+
};
|
|
270
|
+
/**
|
|
271
|
+
* Verifica se a string é um endereço de e-mail válido.
|
|
272
|
+
* @returns true se a string é um e-mail válido, false caso contrário
|
|
273
|
+
* @example
|
|
274
|
+
* "user@example.com".isEmail() // true
|
|
275
|
+
* "invalid-email".isEmail() // false
|
|
276
|
+
*/
|
|
277
|
+
String.prototype.isEmail = function () {
|
|
278
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.valueOf());
|
|
279
|
+
};
|
|
280
|
+
/**
|
|
281
|
+
* Verifica se a string é uma URL válida.
|
|
282
|
+
* @returns true se a string é uma URL válida, false caso contrário
|
|
283
|
+
* @example
|
|
284
|
+
* "https://example.com".isURL() // true
|
|
285
|
+
* "not a url".isURL() // false
|
|
286
|
+
*/
|
|
287
|
+
String.prototype.isURL = function () {
|
|
288
|
+
try {
|
|
289
|
+
new URL(this.valueOf());
|
|
290
|
+
return true;
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
return false;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
/**
|
|
297
|
+
* Verifica se a string é um UUID (Universally Unique Identifier) válido.
|
|
298
|
+
* @returns true se a string é um UUID válido, false caso contrário
|
|
299
|
+
* @example
|
|
300
|
+
* "550e8400-e29b-41d4-a716-446655440000".isUUID() // true
|
|
301
|
+
* "invalid-uuid".isUUID() // false
|
|
302
|
+
*/
|
|
303
|
+
String.prototype.isUUID = function () {
|
|
304
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(this.valueOf());
|
|
305
|
+
};
|
|
306
|
+
// ==================== Conversão ====================
|
|
307
|
+
/**
|
|
308
|
+
* Converte a string para o formato Base64.
|
|
309
|
+
* @returns String codificada em Base64
|
|
310
|
+
* @example
|
|
311
|
+
* "hello".toBase64() // "aGVsbG8="
|
|
312
|
+
*/
|
|
313
|
+
String.prototype.toBase64 = function () {
|
|
314
|
+
return btoa(this.valueOf());
|
|
35
315
|
};
|
|
316
|
+
/**
|
|
317
|
+
* Decodifica a string do formato Base64.
|
|
318
|
+
* @returns String decodificada do Base64
|
|
319
|
+
* @example
|
|
320
|
+
* "aGVsbG8=".fromBase64() // "hello"
|
|
321
|
+
*/
|
|
36
322
|
String.prototype.fromBase64 = function () {
|
|
37
|
-
return atob(this.
|
|
323
|
+
return atob(this.valueOf());
|
|
38
324
|
};
|
|
@@ -1,9 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Symbol que representa o estado de sucesso em estruturas de dutos.
|
|
3
|
+
* @example
|
|
4
|
+
* const isSuccess = result[SuccessReturn];
|
|
5
|
+
*/
|
|
1
6
|
export declare const SuccessReturn: unique symbol;
|
|
7
|
+
/**
|
|
8
|
+
* Symbol que representa o valor encapsulado em estruturas de dutos.
|
|
9
|
+
* @example
|
|
10
|
+
* const value = result[ValueReturn];
|
|
11
|
+
*/
|
|
2
12
|
export declare const ValueReturn: unique symbol;
|
|
13
|
+
/**
|
|
14
|
+
* Symbol utilitário para armazenar referência de função/valor.
|
|
15
|
+
* @example
|
|
16
|
+
* const fnHolder = { [FnVal]: () => "ok" };
|
|
17
|
+
*/
|
|
3
18
|
export declare const FnVal: unique symbol;
|
|
19
|
+
/**
|
|
20
|
+
* Array vazio imutável para reuso seguro.
|
|
21
|
+
* @example
|
|
22
|
+
* for (const item of EmptyArray) {
|
|
23
|
+
* // não executa
|
|
24
|
+
* }
|
|
25
|
+
*/
|
|
4
26
|
export declare const EmptyArray: readonly any[];
|
|
27
|
+
/**
|
|
28
|
+
* Conjunto de valores considerados falsey no domínio de dutos.
|
|
29
|
+
* @example
|
|
30
|
+
* const x: FalseyValues = "";
|
|
31
|
+
* const y: FalseyValues = 0;
|
|
32
|
+
*/
|
|
5
33
|
export type FalseyValues = false | null | undefined | 0 | 0n | "";
|
|
34
|
+
/**
|
|
35
|
+
* Verifica se um valor deve ser tratado como "truthy".
|
|
36
|
+
* - Para Date, valida se o timestamp é válido (não-NaN).
|
|
37
|
+
* - Para demais tipos, usa coerção booleana.
|
|
38
|
+
*
|
|
39
|
+
* @param val Valor a ser verificado.
|
|
40
|
+
* @returns true quando o valor é considerado válido/truthy.
|
|
41
|
+
* @example
|
|
42
|
+
* isTruthy("abc"); // true
|
|
43
|
+
* isTruthy(""); // false
|
|
44
|
+
* isTruthy(new Date()); // true
|
|
45
|
+
* isTruthy(new Date("invalid")); // false
|
|
46
|
+
*/
|
|
6
47
|
export declare function isTruthy(val: unknown): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Extrai o tipo do iterador de um tipo iterável.
|
|
50
|
+
* Retorna `unknown` quando o tipo não for iterável.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* type A = IterType<string[]>; // ArrayIterator<string>
|
|
54
|
+
* type B = IterType<number>; // unknown
|
|
55
|
+
*/
|
|
7
56
|
export type IterType<T> = T extends {
|
|
8
57
|
[Symbol.iterator](): infer I;
|
|
9
58
|
} ? I : unknown;
|
|
@@ -3,12 +3,45 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.EmptyArray = exports.FnVal = exports.ValueReturn = exports.SuccessReturn = void 0;
|
|
4
4
|
exports.isTruthy = isTruthy;
|
|
5
5
|
const guardian_1 = require("../type-guard/guardian");
|
|
6
|
+
/**
|
|
7
|
+
* Symbol que representa o estado de sucesso em estruturas de dutos.
|
|
8
|
+
* @example
|
|
9
|
+
* const isSuccess = result[SuccessReturn];
|
|
10
|
+
*/
|
|
6
11
|
exports.SuccessReturn = Symbol("SuccessReturn");
|
|
12
|
+
/**
|
|
13
|
+
* Symbol que representa o valor encapsulado em estruturas de dutos.
|
|
14
|
+
* @example
|
|
15
|
+
* const value = result[ValueReturn];
|
|
16
|
+
*/
|
|
7
17
|
exports.ValueReturn = Symbol("ValueReturn");
|
|
18
|
+
/**
|
|
19
|
+
* Symbol utilitário para armazenar referência de função/valor.
|
|
20
|
+
* @example
|
|
21
|
+
* const fnHolder = { [FnVal]: () => "ok" };
|
|
22
|
+
*/
|
|
8
23
|
exports.FnVal = Symbol("FnVal");
|
|
24
|
+
/**
|
|
25
|
+
* Array vazio imutável para reuso seguro.
|
|
26
|
+
* @example
|
|
27
|
+
* for (const item of EmptyArray) {
|
|
28
|
+
* // não executa
|
|
29
|
+
* }
|
|
30
|
+
*/
|
|
9
31
|
exports.EmptyArray = Object.freeze([]);
|
|
32
|
+
/**
|
|
33
|
+
* Verifica se um valor deve ser tratado como "truthy".
|
|
34
|
+
* - Para Date, valida se o timestamp é válido (não-NaN).
|
|
35
|
+
* - Para demais tipos, usa coerção booleana.
|
|
36
|
+
*
|
|
37
|
+
* @param val Valor a ser verificado.
|
|
38
|
+
* @returns true quando o valor é considerado válido/truthy.
|
|
39
|
+
* @example
|
|
40
|
+
* isTruthy("abc"); // true
|
|
41
|
+
* isTruthy(""); // false
|
|
42
|
+
* isTruthy(new Date()); // true
|
|
43
|
+
* isTruthy(new Date("invalid")); // false
|
|
44
|
+
*/
|
|
10
45
|
function isTruthy(val) {
|
|
11
|
-
return val instanceof Date
|
|
12
|
-
? guardian_1._.isEqual(val.getTime(), val.getTime())
|
|
13
|
-
: !!val;
|
|
46
|
+
return val instanceof Date ? guardian_1._.isEqual(val.getTime(), val.getTime()) : !!val;
|
|
14
47
|
}
|
|
@@ -1,24 +1,109 @@
|
|
|
1
1
|
import { FalseyValues, IterType, SuccessReturn, ValueReturn } from "./common";
|
|
2
|
+
/**
|
|
3
|
+
* Representa um Optional com valor presente.
|
|
4
|
+
* @example
|
|
5
|
+
* const value = Optional("ok");
|
|
6
|
+
* if (value.hasSomething()) {
|
|
7
|
+
* value.unpack(); // "ok"
|
|
8
|
+
* }
|
|
9
|
+
*/
|
|
2
10
|
export type Something<T> = OptionalType<T> & {
|
|
3
11
|
[SuccessReturn]: true;
|
|
4
12
|
};
|
|
13
|
+
/**
|
|
14
|
+
* Representa um Optional sem valor.
|
|
15
|
+
* @example
|
|
16
|
+
* const value = Optional("");
|
|
17
|
+
* value.hasNothing(); // true
|
|
18
|
+
*/
|
|
5
19
|
export type Nothing = OptionalType<never> & {
|
|
6
20
|
[SuccessReturn]: false;
|
|
7
21
|
};
|
|
22
|
+
/**
|
|
23
|
+
* Tipo principal de Optional.
|
|
24
|
+
* @example
|
|
25
|
+
* const maybeName: Optional<string> = Optional("John");
|
|
26
|
+
*/
|
|
8
27
|
export type Optional<T> = OptionalType<T>;
|
|
9
28
|
type From<T> = Exclude<T, Error | FalseyValues>;
|
|
10
29
|
declare class OptionalType<T> {
|
|
11
30
|
readonly [SuccessReturn]: boolean;
|
|
12
31
|
readonly [ValueReturn]: T;
|
|
32
|
+
/**
|
|
33
|
+
* Cria uma nova instância de OptionalType.
|
|
34
|
+
* @param val Valor interno.
|
|
35
|
+
* @param something Indica presença de valor.
|
|
36
|
+
* @example
|
|
37
|
+
* const some = new (class extends OptionalType<string> {})("x", true);
|
|
38
|
+
*/
|
|
13
39
|
constructor(val: T, something: boolean);
|
|
40
|
+
/**
|
|
41
|
+
* Permite iteração quando houver valor iterável.
|
|
42
|
+
* @example
|
|
43
|
+
* const maybeArr = Optional([1, 2, 3]);
|
|
44
|
+
* for (const n of maybeArr) {
|
|
45
|
+
* // 1, 2, 3
|
|
46
|
+
* }
|
|
47
|
+
*/
|
|
14
48
|
[Symbol.iterator](this: Optional<T>): IterType<T>;
|
|
49
|
+
/**
|
|
50
|
+
* Verifica se existe valor.
|
|
51
|
+
* @returns true se houver valor.
|
|
52
|
+
* @example
|
|
53
|
+
* Optional("abc").hasSomething(); // true
|
|
54
|
+
* Optional("").hasSomething(); // false
|
|
55
|
+
*/
|
|
15
56
|
hasSomething(this: Optional<T>): this is Something<T>;
|
|
57
|
+
/**
|
|
58
|
+
* Verifica se não existe valor.
|
|
59
|
+
* @returns true se não houver valor.
|
|
60
|
+
* @example
|
|
61
|
+
* Optional(null).hasNothing(); // true
|
|
62
|
+
*/
|
|
16
63
|
hasNothing(this: Optional<T>): this is Nothing;
|
|
64
|
+
/**
|
|
65
|
+
* Retorna o valor interno.
|
|
66
|
+
* @throws {Error} Se não houver valor.
|
|
67
|
+
* @example
|
|
68
|
+
* Optional(10).unpack(); // 10
|
|
69
|
+
*/
|
|
17
70
|
unpack(this: Optional<T>): T;
|
|
71
|
+
/**
|
|
72
|
+
* Retorna o valor interno mesmo quando vazio.
|
|
73
|
+
* @returns Valor interno ou undefined.
|
|
74
|
+
* @example
|
|
75
|
+
* Optional("x").unpackAnyway(); // "x"
|
|
76
|
+
* Optional("").unpackAnyway(); // undefined
|
|
77
|
+
*/
|
|
18
78
|
unpackAnyway(this: Optional<T>): T | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Retorna o valor interno ou valor padrão.
|
|
81
|
+
* @param def Valor padrão.
|
|
82
|
+
* @example
|
|
83
|
+
* Optional("").unpackOr("default"); // "default"
|
|
84
|
+
*/
|
|
19
85
|
unpackOr(this: Optional<T>, def: T): T;
|
|
86
|
+
/**
|
|
87
|
+
* Retorna o valor interno ou calcula valor padrão sob demanda.
|
|
88
|
+
* @param f Função para gerar valor padrão.
|
|
89
|
+
* @example
|
|
90
|
+
* Optional("").unpackOrElse(() => "fallback"); // "fallback"
|
|
91
|
+
*/
|
|
20
92
|
unpackOrElse(this: Optional<T>, f: () => T): T;
|
|
21
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Cria um Optional a partir de um valor.
|
|
96
|
+
* Valores falsey e Error resultam em Nothing.
|
|
97
|
+
* @param val Valor de entrada.
|
|
98
|
+
* @example
|
|
99
|
+
* Optional("abc").hasSomething(); // true
|
|
100
|
+
* Optional(0).hasNothing(); // true
|
|
101
|
+
*/
|
|
22
102
|
export declare function Optional<T>(val: T): Optional<From<T>>;
|
|
103
|
+
/**
|
|
104
|
+
* Singleton representando ausência de valor.
|
|
105
|
+
* @example
|
|
106
|
+
* Nothing.hasNothing(); // true
|
|
107
|
+
*/
|
|
23
108
|
export declare const Nothing: Readonly<OptionalType<never>>;
|
|
24
109
|
export {};
|
|
@@ -4,44 +4,123 @@ exports.Nothing = void 0;
|
|
|
4
4
|
exports.Optional = Optional;
|
|
5
5
|
const common_1 = require("./common");
|
|
6
6
|
class OptionalType {
|
|
7
|
+
/**
|
|
8
|
+
* Cria uma nova instância de OptionalType.
|
|
9
|
+
* @param val Valor interno.
|
|
10
|
+
* @param something Indica presença de valor.
|
|
11
|
+
* @example
|
|
12
|
+
* const some = new (class extends OptionalType<string> {})("x", true);
|
|
13
|
+
*/
|
|
7
14
|
constructor(val, something) {
|
|
8
15
|
this[common_1.SuccessReturn] = something;
|
|
9
16
|
this[common_1.ValueReturn] = val;
|
|
10
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* Permite iteração quando houver valor iterável.
|
|
20
|
+
* @example
|
|
21
|
+
* const maybeArr = Optional([1, 2, 3]);
|
|
22
|
+
* for (const n of maybeArr) {
|
|
23
|
+
* // 1, 2, 3
|
|
24
|
+
* }
|
|
25
|
+
*/
|
|
11
26
|
[Symbol.iterator]() {
|
|
12
27
|
return this[common_1.SuccessReturn]
|
|
13
28
|
? this[common_1.ValueReturn][Symbol.iterator]()
|
|
14
29
|
: common_1.EmptyArray[Symbol.iterator]();
|
|
15
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Verifica se existe valor.
|
|
33
|
+
* @returns true se houver valor.
|
|
34
|
+
* @example
|
|
35
|
+
* Optional("abc").hasSomething(); // true
|
|
36
|
+
* Optional("").hasSomething(); // false
|
|
37
|
+
*/
|
|
16
38
|
hasSomething() {
|
|
17
39
|
return this[common_1.SuccessReturn];
|
|
18
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Verifica se não existe valor.
|
|
43
|
+
* @returns true se não houver valor.
|
|
44
|
+
* @example
|
|
45
|
+
* Optional(null).hasNothing(); // true
|
|
46
|
+
*/
|
|
19
47
|
hasNothing() {
|
|
20
48
|
return !this[common_1.SuccessReturn];
|
|
21
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Retorna o valor interno.
|
|
52
|
+
* @throws {Error} Se não houver valor.
|
|
53
|
+
* @example
|
|
54
|
+
* Optional(10).unpack(); // 10
|
|
55
|
+
*/
|
|
22
56
|
unpack() {
|
|
23
57
|
if (this[common_1.SuccessReturn]) {
|
|
24
58
|
return this[common_1.ValueReturn];
|
|
25
59
|
}
|
|
26
60
|
throw new Error("Failed to unpack optional value. There is nothing in here");
|
|
27
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Retorna o valor interno mesmo quando vazio.
|
|
64
|
+
* @returns Valor interno ou undefined.
|
|
65
|
+
* @example
|
|
66
|
+
* Optional("x").unpackAnyway(); // "x"
|
|
67
|
+
* Optional("").unpackAnyway(); // undefined
|
|
68
|
+
*/
|
|
28
69
|
unpackAnyway() {
|
|
29
70
|
return this[common_1.ValueReturn];
|
|
30
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Retorna o valor interno ou valor padrão.
|
|
74
|
+
* @param def Valor padrão.
|
|
75
|
+
* @example
|
|
76
|
+
* Optional("").unpackOr("default"); // "default"
|
|
77
|
+
*/
|
|
31
78
|
unpackOr(def) {
|
|
32
79
|
return this[common_1.SuccessReturn] ? this[common_1.ValueReturn] : def;
|
|
33
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Retorna o valor interno ou calcula valor padrão sob demanda.
|
|
83
|
+
* @param f Função para gerar valor padrão.
|
|
84
|
+
* @example
|
|
85
|
+
* Optional("").unpackOrElse(() => "fallback"); // "fallback"
|
|
86
|
+
*/
|
|
34
87
|
unpackOrElse(f) {
|
|
35
88
|
return this[common_1.SuccessReturn] ? this[common_1.ValueReturn] : f();
|
|
36
89
|
}
|
|
37
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* Cria um Optional a partir de um valor.
|
|
93
|
+
* Valores falsey e Error resultam em Nothing.
|
|
94
|
+
* @param val Valor de entrada.
|
|
95
|
+
* @example
|
|
96
|
+
* Optional("abc").hasSomething(); // true
|
|
97
|
+
* Optional(0).hasNothing(); // true
|
|
98
|
+
*/
|
|
38
99
|
function Optional(val) {
|
|
39
100
|
return from(val);
|
|
40
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Cria um Optional no estado Something.
|
|
104
|
+
* @param val Valor presente.
|
|
105
|
+
* @example
|
|
106
|
+
* const some = Something("ok");
|
|
107
|
+
*/
|
|
41
108
|
function Something(val) {
|
|
42
109
|
return new OptionalType(val, true);
|
|
43
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Singleton representando ausência de valor.
|
|
113
|
+
* @example
|
|
114
|
+
* Nothing.hasNothing(); // true
|
|
115
|
+
*/
|
|
44
116
|
exports.Nothing = Object.freeze(new OptionalType(undefined, false));
|
|
117
|
+
/**
|
|
118
|
+
* Converte valor para Optional conforme regra de truthy.
|
|
119
|
+
* @param val Valor de entrada.
|
|
120
|
+
* @example
|
|
121
|
+
* from("x").hasSomething(); // true
|
|
122
|
+
* from(false).hasNothing(); // true
|
|
123
|
+
*/
|
|
45
124
|
function from(val) {
|
|
46
125
|
return (0, common_1.isTruthy)(val) && !(val instanceof Error)
|
|
47
126
|
? Something(val)
|