npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

korusjs

v1.0.0

Published

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.

Downloads

542

Readme

🦊 korusjs

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.

Nota: Esta biblioteca foi reescrita em JavaScript puro para máxima performance e liberdade criativa, deixando para trás a burocracia do TypeScript.


🚀 Instalação

npm install @leojsandkotdev/korusjs

🛠️ Como usar

O básico com optionOf

O optionOf é o porteiro da biblioteca.
Ele aceita valores brutos, Some ou nothing e decide o resultado final.

  • null, undefined ou nothing → retorna nothing
  • null, undefined ou nothing + fallback → retorna Some(fallback)
  • Some → retorna o próprio Some
  • qualquer outro valor → retorna Some(valor)
import { optionOf } from '@leojsandkotdev/korusjs';

// Com valor real
const user = optionOf("Leo", "nada"); 

// Com valor nulo ou indefinido
const empty = optionOf(null, "vazio"); 

// Com valor padrão (fallback)
const name = optionOf(null, "Visitante"); // Retorna Some("Visitante")

Encadeamento Inteligente (Chaining)

Esqueça os erros de Cannot read property of undefined. Com a korusjs, você encadeia operações com segurança:

const result = optionOf("  123.45  ", 0.0)
    .map(s => s.trim())     // Remove espaços
    .toFloat()              // Converte para Float com validação interna
    .map(n => n * 2)        // Multiplica o valor
    .unwrapOr(0);           // Se algo falhar (ex: string inválida), retorna 0

console.log(result); // 246.9

Verificações e Fluxo

Controle a execução do seu programa de forma elegante:

const opt = optionOf(someValue, fallback);

if (opt.isSome()) {
    console.log("Temos dados!");
}

opt.ifPresent(v => console.log("Valor presente:", v))
   .onNothing(() => console.log("Opa, não tem nada aqui!"));

📖 API

| Método | Descrição | | :--- | :--- | | map(fn) | Transforma o valor interno e retorna um novo Some. | | filter(cond) | Retorna nothing se a condição não for atendida. | | toInt() | Converte para Inteiro. Retorna nothing se falhar. | | toFloat() | Converte para Float. Retorna nothing se falhar ou for Infinito. | | unwrapOr(val) | Retorna o valor interno ou o valor padrão fornecido. | | unwrapOrElse(fn) | Executa a função apenas se for nothing e retorna o valor produzido. | | isSome() | Retorna true se for uma instância da classe Some(). | | isNothing() | Retorna true se for uma instância nothing | | finalize() | ⚠️ Extrai o valor bruto. Lança erro se for chamado em um nothing. | | ifPresent(fn) | Executa a função se houver valor(Some()). Ideal para side-effects. | | onNothing(fn) | Executa a função se estiver vazio (nothing). Ideal para consequências/erros. |

nothing é um singleton (instância única) que representa a ausência segura de valor.
Nothing é a classe interna usada pela biblioteca para implementar esse comportamento. ⚠️finalize() deve ser usado quando optionOf recebe um valor padrão, garantindo que a cadeia sempre resulte em um valor válido. Exemplo abaixo:

const valor = Some("42")
  .toInt()
  .filter(n => n > 0)
  .map(n => n * 2)
  .ifPresent(console.log)
  .onNothing(() => console.error("Valor inválido"))
  .finalize()

💡 Filosofia

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.

Desenvolvido por @leojsandkotdev.