korusjs 1.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/.si.json +11 -0
- package/README.md +101 -0
- package/index.js +2 -0
- package/option.js +160 -0
- package/package.json +13 -0
package/.si.json
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# 🦊 korusjs
|
|
2
|
+
|
|
3
|
+
Uma biblioteca minimalista, leve e poderosa para lidar com valores nulos e indefinidos no JavaScript. Inspirada no padrão `Option` do Rust e Kotlin, a **korusjs** traz segurança para o seu código sem a necessidade de compiladores complexos.
|
|
4
|
+
|
|
5
|
+
> **Nota:** Esta biblioteca foi reescrita em JavaScript puro para máxima performance e liberdade criativa, deixando para trás a burocracia do TypeScript.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 🚀 Instalação
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @leojsandkotdev/korusjs
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## 🛠️ Como usar
|
|
16
|
+
|
|
17
|
+
### O básico com `optionOf`
|
|
18
|
+
O `optionOf` é o porteiro da biblioteca.
|
|
19
|
+
Ele aceita valores brutos, `Some` ou `nothing` e decide o resultado final.
|
|
20
|
+
|
|
21
|
+
- `null`, `undefined` ou `nothing` → retorna `nothing`
|
|
22
|
+
- `null`, `undefined` ou `nothing` + fallback → retorna `Some(fallback)`
|
|
23
|
+
- `Some` → retorna o próprio `Some`
|
|
24
|
+
- qualquer outro valor → retorna `Some(valor)`
|
|
25
|
+
|
|
26
|
+
```javascript
|
|
27
|
+
import { optionOf } from '@leojsandkotdev/korusjs';
|
|
28
|
+
|
|
29
|
+
// Com valor real
|
|
30
|
+
const user = optionOf("Leo", "nada");
|
|
31
|
+
|
|
32
|
+
// Com valor nulo ou indefinido
|
|
33
|
+
const empty = optionOf(null, "vazio");
|
|
34
|
+
|
|
35
|
+
// Com valor padrão (fallback)
|
|
36
|
+
const name = optionOf(null, "Visitante"); // Retorna Some("Visitante")
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Encadeamento Inteligente (Chaining)
|
|
40
|
+
Esqueça os erros de `Cannot read property of undefined`. Com a korusjs, você encadeia operações com segurança:
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
const result = optionOf(" 123.45 ", 0.0)
|
|
44
|
+
.map(s => s.trim()) // Remove espaços
|
|
45
|
+
.toFloat() // Converte para Float com validação interna
|
|
46
|
+
.map(n => n * 2) // Multiplica o valor
|
|
47
|
+
.unwrapOr(0); // Se algo falhar (ex: string inválida), retorna 0
|
|
48
|
+
|
|
49
|
+
console.log(result); // 246.9
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Verificações e Fluxo
|
|
53
|
+
Controle a execução do seu programa de forma elegante:
|
|
54
|
+
|
|
55
|
+
```javascript
|
|
56
|
+
const opt = optionOf(someValue, fallback);
|
|
57
|
+
|
|
58
|
+
if (opt.isSome()) {
|
|
59
|
+
console.log("Temos dados!");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
opt.ifPresent(v => console.log("Valor presente:", v))
|
|
63
|
+
.onNothing(() => console.log("Opa, não tem nada aqui!"));
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 📖 API
|
|
69
|
+
|
|
70
|
+
| Método | Descrição |
|
|
71
|
+
| :--- | :--- |
|
|
72
|
+
| `map(fn)` | Transforma o valor interno e retorna um novo `Some`. |
|
|
73
|
+
| `filter(cond)` | Retorna `nothing` se a condição não for atendida. |
|
|
74
|
+
| `toInt()` | Converte para Inteiro. Retorna `nothing` se falhar. |
|
|
75
|
+
| `toFloat()` | Converte para Float. Retorna `nothing` se falhar ou for Infinito. |
|
|
76
|
+
| `unwrapOr(val)` | Retorna o valor interno ou o valor padrão fornecido. |
|
|
77
|
+
| `unwrapOrElse(fn)` | Executa a função apenas se for `nothing` e retorna o valor produzido. |
|
|
78
|
+
| `isSome()` | Retorna `true` se for uma instância da classe `Some()`. |
|
|
79
|
+
| `isNothing()` | Retorna `true` se for uma instância `nothing` |
|
|
80
|
+
| `finalize()` | ⚠️ Extrai o valor bruto. Lança erro se for chamado em um `nothing`. |
|
|
81
|
+
| `ifPresent(fn)` | Executa a função se houver valor(`Some()`). Ideal para side-effects. |
|
|
82
|
+
| `onNothing(fn)` | Executa a função se estiver vazio (`nothing`). Ideal para consequências/erros. |
|
|
83
|
+
> `nothing` é um singleton (instância única) que representa a ausência segura de valor.
|
|
84
|
+
> `Nothing` é a classe interna usada pela biblioteca para implementar esse comportamento.
|
|
85
|
+
> ⚠️`finalize()` deve ser usado quando optionOf recebe um valor padrão, garantindo que a cadeia sempre resulte em um valor válido.
|
|
86
|
+
> Exemplo abaixo:
|
|
87
|
+
```javascript
|
|
88
|
+
const valor = Some("42")
|
|
89
|
+
.toInt()
|
|
90
|
+
.filter(n => n > 0)
|
|
91
|
+
.map(n => n * 2)
|
|
92
|
+
.ifPresent(console.log)
|
|
93
|
+
.onNothing(() => console.error("Valor inválido"))
|
|
94
|
+
.finalize()
|
|
95
|
+
```
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## 💡 Filosofia
|
|
99
|
+
A **korusjs** foi feita para quem quer escrever código limpo e robusto rapidamente. É o equilíbrio perfeito entre a flexibilidade do JavaScript e a segurança de tipos das linguagens modernas.
|
|
100
|
+
|
|
101
|
+
Desenvolvido por **@leojsandkotdev**.
|
package/index.js
ADDED
package/option.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
export class Nothing{
|
|
2
|
+
constructor(){
|
|
3
|
+
if(Nothing.instance){
|
|
4
|
+
return Nothing.instance;
|
|
5
|
+
}
|
|
6
|
+
Nothing.instance = this;
|
|
7
|
+
}
|
|
8
|
+
map(fn){
|
|
9
|
+
return this;
|
|
10
|
+
}
|
|
11
|
+
toFloat(){
|
|
12
|
+
return this;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
toInt(){
|
|
16
|
+
return this;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
filter(fn){
|
|
20
|
+
return this;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
getValue(){
|
|
24
|
+
return this;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
andThen(fn){
|
|
28
|
+
return this;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
unwrapOrElse(fn){
|
|
32
|
+
fn();
|
|
33
|
+
return this;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
unwrapOr(defaultValue){
|
|
37
|
+
if(defaultValue != null){
|
|
38
|
+
return defaultValue
|
|
39
|
+
}else{
|
|
40
|
+
return this
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
finalize(){
|
|
45
|
+
throw new Error("tried to finalize nothing, try using methods like `getValue()`, `unwrapOr()` or `unwrapOrElse()`.")
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
isSome(){
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
isNothing(){
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
ifPresent(fn){
|
|
56
|
+
return this;
|
|
57
|
+
}
|
|
58
|
+
onNothing(fn){
|
|
59
|
+
fn();
|
|
60
|
+
return this;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export const nothing = new Nothing();
|
|
64
|
+
Object.freeze(nothing);
|
|
65
|
+
|
|
66
|
+
export class Some{
|
|
67
|
+
constructor(value){
|
|
68
|
+
this.value = value;
|
|
69
|
+
}
|
|
70
|
+
finalize(){
|
|
71
|
+
return this.value
|
|
72
|
+
}
|
|
73
|
+
ifPresent(fn){
|
|
74
|
+
fn();
|
|
75
|
+
return new Some(this.value);
|
|
76
|
+
}
|
|
77
|
+
onNothing(fn){
|
|
78
|
+
return this;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
toFloat(){
|
|
82
|
+
const result = parseFloat(this.value)
|
|
83
|
+
if(!Number.isFinite(result)){
|
|
84
|
+
return nothing
|
|
85
|
+
}
|
|
86
|
+
return new Some(result);
|
|
87
|
+
}
|
|
88
|
+
toInt(){
|
|
89
|
+
const result = parseInt(this.value)
|
|
90
|
+
if(Number.isNaN(result)){
|
|
91
|
+
return nothing;
|
|
92
|
+
}
|
|
93
|
+
return new Some(result);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
getValue(){
|
|
97
|
+
return new Some(this.value)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
unwrapOr(defaultValue){
|
|
101
|
+
return this.value
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
unwrapOrElse(fn){
|
|
105
|
+
return this.value
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
map(fn){
|
|
109
|
+
if(fn != null){
|
|
110
|
+
return new Some(fn(this.value));
|
|
111
|
+
}else{
|
|
112
|
+
return nothing
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
filter(condition){
|
|
117
|
+
if(condition(this.value)){
|
|
118
|
+
return new Some(this.value);
|
|
119
|
+
}
|
|
120
|
+
return nothing;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
andThen(fn){
|
|
124
|
+
fn()
|
|
125
|
+
return new Some(this.value)
|
|
126
|
+
}
|
|
127
|
+
isSome(){
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
isNothing(){
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function warn(message) {
|
|
135
|
+
if (typeof console !== "undefined" && console.warn) {
|
|
136
|
+
console.warn(`[korusjs] ${message}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
export function optionOf(value, defaultValue = nothing) {
|
|
140
|
+
// Determina se o value é considerado "ausente"
|
|
141
|
+
const isAbsent =
|
|
142
|
+
value == null ||
|
|
143
|
+
value === nothing ||
|
|
144
|
+
(value.isNothing && value.isNothing());
|
|
145
|
+
|
|
146
|
+
if (isAbsent) {
|
|
147
|
+
// Se existe fallback válido, retorna Some(fallback)
|
|
148
|
+
if (defaultValue != null && defaultValue !== nothing) {
|
|
149
|
+
return new Some(defaultValue);
|
|
150
|
+
}
|
|
151
|
+
// Caso contrário, dispara warning e retorna nothing
|
|
152
|
+
warn(
|
|
153
|
+
"Security warning: the optionOf function returned nothing and the default was not set. Avoid using `finalize()` in this case."
|
|
154
|
+
);
|
|
155
|
+
return nothing;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Se value já é válido, encapsula em Some
|
|
159
|
+
return new Some(value);
|
|
160
|
+
}
|
package/package.json
ADDED