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 🙏

© 2026 – Pkg Stats / Ryan Hefner

ubigeo-fns

v2.2.0

Published

Funciones utilitarias para trabajar con ubigeos del Perú en JavaScript y TypeScript.

Readme

ubigeo-fns

npm version npm downloads bundle size Security

Funciones utilitarias para trabajar con ubigeos del Perú en JavaScript y TypeScript.
Basado en datos oficiales del INEI (Instituto Nacional de Estadística e Informática).

Fuente de datos

Los datos de ubigeos incluidos en este paquete provienen del INEI (códigos de departamentos, provincias y distritos del Perú) y se complementan con información geográfica (coordenadas, población y área) extraída de fuentes oficiales. Referencia: INEI - Códigos de ubigeo

Características

  • Obtener distrito, provincia y departamento por código UBIGEO
  • Acceder a información completa del ubigeo (coordenadas, población, área)
  • Validar códigos UBIGEO (departamento, provincia, distrito)
  • Formatear ubigeos en texto listo para UI
  • Parsear códigos UBIGEO en estructura jerárquica
  • Búsqueda por nombre (searchByName) con coincidencia parcial y límite de resultados
  • Flexibilidad de entrada: Soporta códigos en formato numérico o texto (ej: 150131 o "150131")
  • Soporte para códigos cortos: getDepartment y getProvince aceptan códigos de 2 y 4 dígitos respectivamente
  • Búsquedas optimizadas con estructuras O(1)
  • Compatible con JavaScript y TypeScript
  • Optimizado para Node.js, React y bundlers modernos
  • Soporta tree-shaking y minificación

Casos de uso

  • Formularios con selects dependientes (departamento → provincia → distrito)
  • Validación de direcciones en sistemas de facturación electrónica (Sunat)
  • Apps de delivery y logística
  • Dashboards geográficos
  • Normalización de ubicaciones en Perú
  • Sistemas de registro de personas y empresas

Instalación

npm install ubigeo-fns
# o usando yarn
yarn add ubigeo-fns

Uso rápido

import {
  getDistrict,
  getProvince,
  getDepartment,
  validateUbigeo,
  formatUbigeo,
  searchByName
} from "ubigeo-fns";

// Obtener jerarquía geográfica
const ubigeo = "150131";

getDepartment(ubigeo); // "Lima"
getProvince(ubigeo);   // "Lima"
getDistrict(ubigeo);   // "San Isidro"

// Validar código
validateUbigeo(ubigeo); // true

// Formatear para UI
formatUbigeo(ubigeo);         // "San Isidro, Lima, Lima"
formatUbigeo(ubigeo, "short");// "San Isidro, Lima"

// Búsqueda por nombre (devuelve hasta 50 resultados por defecto)
searchByName("San Isidro");   // [{ ubigeo: "150131", district: "San Isidro", ... }]

// Búsqueda con límite personalizado
searchByName("San", { limit: 10 }); // Devuelve hasta 10 resultados

API completa

import {
  getDistrict,
  getProvince,
  getDepartment,
  getDepartments,
  getProvinces,
  getDistricts,
  validateUbigeo,
  getUbigeoData,
  parseUbigeo,
  formatUbigeo,
  isValidDepartment,
  isValidProvince,
  isValidDistrict,
  searchByName
} from "ubigeo-fns";

// Obtener listas jerárquicas
getDepartments();   // [{ code: "15", name: "Lima" }, ...]
getProvinces("15"); // [{ code: "1501", name: "Lima" }, ...]
getDistricts("1501"); // [{ code: "150131", name: "San Isidro" }, ...]

// Información completa
const data = getUbigeoData("150131");
// {
//   ubigeo: "150131",
//   district: "San Isidro",
//   province: "Lima",
//   department: "Lima",
//   population: 60367,
//   area: 9.36,
//   lat: -12.0989,
//   lng: -77.0434
// }

// Parsear códigos
parseUbigeo("150131");
// { departmentCode: "15", provinceCode: "1501", districtCode: "150131" }

// Validaciones específicas
isValidDepartment("15");   // true
isValidProvince("1501");   // true
isValidDistrict("150131"); // true

Tipos TypeScript

interface UbigeoData {
  ubigeo: string;      // Código de 6 dígitos
  district: string;    // Nombre del distrito
  province: string;    // Nombre de la provincia
  department: string;  // Nombre del departamento
  population: number;  // Población (fuente: INEI)
  area: number;        // Área en km²
  lat: number;         // Latitud
  lng: number;         // Longitud
}

Funciones disponibles

| Función | Descripción | Parámetros | Retorno | | --------------------- | ------------------------------------------ | -------------------------------------------- | -------------------- | | getDepartment() | Devuelve el nombre del departamento | ubigeo: string | string | | getProvince() | Devuelve el nombre de la provincia | ubigeo: string | string | | getDistrict() | Devuelve el nombre del distrito | ubigeo: string | string | | getDepartments() | Lista todos los departamentos | - | { code, name }[] | | getProvinces() | Lista provincias por departamento | code: string| { code, name }[] | | getDistricts() | Lista distritos por provincia | code: string| { code, name }[] | | validateUbigeo() | Valida si el UBIGEO existe | ubigeo: string | boolean | | getUbigeoData() | Devuelve toda la información del ubigeo | ubigeo: string | UbigeoData \| null | | parseUbigeo() | Separa el ubigeo en códigos jerárquicos | ubigeo: string | object \| null | | formatUbigeo() | Devuelve el ubigeo formateado | ubigeo: string \| number, format?: 'full' \| 'short' | string \| null | | searchByName() | Búsqueda por nombre | name: string, options?: { limit?: number } | SearchResult[] | | isValidDepartment() | Valida si el código de departamento existe | code: string | boolean | | isValidProvince() | Valida si el código de provincia existe | code: string | boolean | | isValidDistrict() | Valida si el código de distrito existe | code: string | boolean |

Desarrollo y build

El proyecto está preparado con tsup para builds optimizados:

npm run build
  • Genera dist/ con ESM + TypeScript types
  • Minificado y optimizado
  • Listo para publicar en npm

Tamaño del bundle

Este paquete incluye el dataset completo de ubigeos con información geográfica (~245KB).

  • Recomendado para Node.js, backend y aplicaciones empresariales
  • Para aplicaciones frontend, considera lazy loading si el tamaño es crítico
  • El tree-shaking es compatible, pero el dataset es compartido entre funciones

Documentación Adicional

Changelog

Ver CHANGELOG.md para el historial de versiones.

Licencia

MIT © 2026 Franco Caballero LICENSE

Enlaces