universal-unit
v1.0.8
Published
A lightweight unit and currency conversion utility
Downloads
823
Maintainers
Readme
🌍 Universal Unit
Universal Unit is a lightweight, zero-dependency unit conversion utility for JavaScript and TypeScript applications.
Convert values across multiple measurement categories using one simple, consistent API.
From length and weight to area, volume, data, speed, time, and pressure, Universal Unit provides accurate conversions without requiring external dependencies.
✨ Features
- 🚀 Lightweight and fast
- 📦 Zero runtime dependencies
- 💙 JavaScript & TypeScript friendly
- 📏 Length conversion
- ⚖️ Weight conversion
- 📐 Area conversion
- 🧪 Volume conversion
- 💾 Data storage conversion
- 🏎️ Speed conversion
- ⏱️ Time conversion
- 🌡️ Pressure conversion
- 🔄 One unified conversion function
- 🧩 Multiple aliases for commonly used units
- 🛡️ Built-in validation for categories and units
- 📘 Fully typed TypeScript API
- 🔧 Easy to integrate into any Node.js or JavaScript project
📦 Installation
Install Universal Unit using npm:
npm install universal-unit🚀 Quick Start
Import convertUnit and provide the value, source unit, target unit, and category.
import { convertUnit } from 'universal-unit';
const result = convertUnit({
value: 5,
from: 'km',
to: 'm',
category: 'length',
});
console.log(result);
// 5000The same function works across all supported categories.
📚 Supported Categories
Universal Unit currently supports:
| Category | Description |
| ---------- | -------------------------- |
| length | Length and distance |
| weight | Weight and mass |
| area | Area measurements |
| volume | Volume measurements |
| data | Digital data/storage units |
| speed | Speed measurements |
| time | Time measurements |
| pressure | Pressure measurements |
📏 Length
Supported length units:
| Unit | Description |
| ------ | ------------- |
| nm | Nanometer |
| um | Micrometer |
| mm | Millimeter |
| cm | Centimeter |
| dm | Decimeter |
| m | Meter |
| km | Kilometer |
| in | Inch |
| ft | Foot |
| yd | Yard |
| mile | Mile |
| nmi | Nautical Mile |
Example
import { convertUnit } from 'universal-unit';
const meters = convertUnit({
value: 5,
from: 'km',
to: 'm',
category: 'length',
});
console.log(meters);
// 5000⚖️ Weight
Supported weight units:
| Unit | Description |
| ----- | ----------- |
| mcg | Microgram |
| mg | Milligram |
| g | Gram |
| kg | Kilogram |
| ton | Metric Ton |
| oz | Ounce |
| lb | Pound |
| st | Stone |
Example
const grams = convertUnit({
value: 5,
from: 'kg',
to: 'g',
category: 'weight',
});
console.log(grams);
// 5000📐 Area
Supported area units include:
| Unit | Description |
| ------------------- | ----------------- |
| square_meter | Square Meter |
| sq_m | Square Meter |
| m2 | Square Meter |
| square_kilometer | Square Kilometer |
| sq_km | Square Kilometer |
| km2 | Square Kilometer |
| square_centimeter | Square Centimeter |
| sq_cm | Square Centimeter |
| cm2 | Square Centimeter |
| square_millimeter | Square Millimeter |
| sq_mm | Square Millimeter |
| mm2 | Square Millimeter |
| hectare | Hectare |
| ha | Hectare |
| acre | Acre |
| square_mile | Square Mile |
| sq_mi | Square Mile |
| mi2 | Square Mile |
| square_yard | Square Yard |
| sq_yd | Square Yard |
| yd2 | Square Yard |
| square_foot | Square Foot |
| sq_ft | Square Foot |
| ft2 | Square Foot |
| square_inch | Square Inch |
| sq_in | Square Inch |
| in2 | Square Inch |
Example
const acres = convertUnit({
value: 10000,
from: 'square_meter',
to: 'acre',
category: 'area',
});
console.log(acres);🧪 Volume
Supported volume units:
| Unit | Description |
| ------------------ | ---------------- |
| cubic_meter | Cubic Meter |
| m3 | Cubic Meter |
| liter | Liter |
| litre | Litre |
| l | Liter |
| milliliter | Milliliter |
| ml | Milliliter |
| cubic_centimeter | Cubic Centimeter |
| cm3 | Cubic Centimeter |
| cc | Cubic Centimeter |
| cubic_inch | Cubic Inch |
| in3 | Cubic Inch |
| cubic_foot | Cubic Foot |
| ft3 | Cubic Foot |
| gallon | Gallon |
| gal | Gallon |
| quart | Quart |
| qt | Quart |
| pint | Pint |
| pt | Pint |
| cup | Cup |
| fluid_ounce | Fluid Ounce |
| floz | Fluid Ounce |
Example
const liters = convertUnit({
value: 2,
from: 'gallon',
to: 'liter',
category: 'volume',
});
console.log(liters);💾 Data
Convert between digital storage units using binary-based conversion values.
Supported units:
| Unit | Description |
| ---------- | ----------- |
| byte | Byte |
| b | Byte |
| kilobyte | Kilobyte |
| kb | Kilobyte |
| megabyte | Megabyte |
| mb | Megabyte |
| gigabyte | Gigabyte |
| gb | Gigabyte |
| terabyte | Terabyte |
| tb | Terabyte |
| petabyte | Petabyte |
| pb | Petabyte |
Example
const megabytes = convertUnit({
value: 1,
from: 'gb',
to: 'mb',
category: 'data',
});
console.log(megabytes);
// 1024🏎️ Speed
Supported speed units:
| Unit | Description |
| -------------------- | ------------------ |
| meter_per_second | Meter per Second |
| m/s | Meter per Second |
| kilometer_per_hour | Kilometer per Hour |
| km/h | Kilometer per Hour |
| mile_per_hour | Mile per Hour |
| mph | Mile per Hour |
| knot | Knot |
| kn | Knot |
| foot_per_second | Foot per Second |
| ft/s | Foot per Second |
Example
const kmh = convertUnit({
value: 10,
from: 'm/s',
to: 'km/h',
category: 'speed',
});
console.log(kmh);⏱️ Time
Supported time units:
| Unit | Description |
| -------- | ----------- |
| second | Second |
| s | Second |
| sec | Second |
| minute | Minute |
| min | Minute |
| hour | Hour |
| h | Hour |
| hr | Hour |
| day | Day |
| d | Day |
| week | Week |
| w | Week |
| year | Year |
| yr | Year |
Example
const seconds = convertUnit({
value: 2,
from: 'hour',
to: 'second',
category: 'time',
});
console.log(seconds);
// 7200🌡️ Pressure
Supported pressure units:
| Unit | Description |
| ------------ | ---------------------- |
| pascal | Pascal |
| pa | Pascal |
| kilopascal | Kilopascal |
| kpa | Kilopascal |
| bar | Bar |
| psi | Pounds per Square Inch |
| atmosphere | Standard Atmosphere |
| atm | Standard Atmosphere |
| torr | Torr |
Example
const psi = convertUnit({
value: 1,
from: 'bar',
to: 'psi',
category: 'pressure',
});
console.log(psi);🔧 API Reference
convertUnit()
The main conversion function.
Syntax
convertUnit({
value,
from,
to,
category,
});Parameters
| Parameter | Type | Description |
| ---------- | -------------- | ------------------------ |
| value | number | Numeric value to convert |
| from | string | Source unit |
| to | string | Target unit |
| category | UnitCategory | Conversion category |
Example
const result = convertUnit({
value: 100,
from: 'cm',
to: 'm',
category: 'length',
});
console.log(result);
// 1🛡️ Error Handling
Universal Unit validates both the conversion category and the requested units.
Invalid Category
convertUnit({
value: 10,
from: 'km',
to: 'm',
category: 'invalid',
});This throws an error similar to:
Invalid category: "invalid"Invalid Unit
convertUnit({
value: 10,
from: 'invalid',
to: 'm',
category: 'length',
});This throws an error similar to:
Invalid unit conversion from "invalid" to "m" in category "length"This makes invalid conversions easier to identify during development.
🔤 Unit Aliases
Universal Unit supports multiple aliases for many units.
For example, these all represent the same length unit:
'meter''m'Similarly, area supports aliases such as:
'square_meter'
'sq_m'
'm2'And data supports:
'megabyte'
'mb'This makes the API flexible while keeping conversion calls simple.
💻 TypeScript Support
Universal Unit is designed with TypeScript support in mind.
The package exposes typed conversion parameters and categories.
The available categories are represented by:
type UnitCategory =
| 'length'
| 'weight'
| 'area'
| 'volume'
| 'data'
| 'speed'
| 'time'
| 'pressure';The conversion parameters are:
interface ConvertUnitParams {
value: number;
from: string;
to: string;
category: UnitCategory;
}This provides better developer experience and editor autocomplete when working with TypeScript.
🌟 Why Universal Unit?
Instead of implementing separate conversion functions for every measurement type, Universal Unit provides a single consistent API:
convertUnit({
value: 5,
from: 'km',
to: 'm',
category: 'length',
});The same pattern works for every supported category:
convertUnit({
value: 5,
from: 'kg',
to: 'g',
category: 'weight',
});convertUnit({
value: 10,
from: 'm2',
to: 'sq_ft',
category: 'area',
});convertUnit({
value: 1,
from: 'gb',
to: 'mb',
category: 'data',
});convertUnit({
value: 2,
from: 'hour',
to: 'minute',
category: 'time',
});One API. Multiple conversion categories.
🎯 Use Cases
Universal Unit can be used in:
- 🛒 E-commerce applications
- 📊 Dashboards
- 🧮 Calculator applications
- 🌍 International applications
- 📦 Logistics applications
- 🏭 Business applications
- 📐 Engineering tools
- 💾 Storage calculators
- ⏱️ Time utilities
- 🚗 Speed calculators
- 🌡️ Scientific utilities
- 📱 Web applications
- 🖥️ Node.js applications
- 🔧 Developer tools
- 📚 Educational applications
💱 Currency Conversion
Universal Unit supports currency conversion using live exchange rates provided by the Frankfurter API.
Currency codes are normalized automatically to uppercase, so both uppercase and lowercase inputs are accepted.
import { convertCurrency } from 'universal-unit';
const result = await convertCurrency(100, 'USD', 'INR');
console.log(result);Function Signature
convertCurrency(
amount: number,
from: string,
to: string
): Promise<number>| Parameter | Type | Description |
| --------- | -------- | -------------------- |
| amount | number | Amount to convert |
| from | string | Source currency code |
| to | string | Target currency code |
Example
const usdToInr = await convertCurrency(100, 'USD', 'INR');
console.log(usdToInr);Lowercase currency codes are also supported:
const result = await convertCurrency(100, 'usd', 'inr');
console.log(result);🌍 Supported Currency Codes
The currency conversion function can be used with the currency codes supported by the underlying Frankfurter exchange-rate service.
Major Currencies
| Code | Currency |
| ----- | ------------------ |
| USD | US Dollar |
| EUR | Euro |
| GBP | British Pound |
| INR | Indian Rupee |
| JPY | Japanese Yen |
| CNY | Chinese Yuan |
| AUD | Australian Dollar |
| CAD | Canadian Dollar |
| CHF | Swiss Franc |
| NZD | New Zealand Dollar |
| SGD | Singapore Dollar |
| HKD | Hong Kong Dollar |
| KRW | South Korean Won |
Full Currency Code List
AUD
BGN
BRL
CAD
CHF
CNY
CZK
DKK
EUR
GBP
HKD
HUF
IDR
ILS
INR
ISK
JPY
KRW
MXN
MYR
NOK
NZD
PHP
PLN
RON
SEK
SGD
THB
TRY
USD
ZARNote: Currency availability is determined by the exchange-rate provider. The available currencies and supported currency pairs may change over time.
⚡ Currency Rate Caching
Universal Unit automatically caches exchange rates for 1 hour.
For example:
const first = await convertCurrency(100, 'USD', 'INR');
const second = await convertCurrency(200, 'USD', 'INR');After the first request, the USD → INR rate is stored in memory.
As long as the cached rate is less than one hour old, subsequent conversions using the same currency pair use the cached rate instead of making another API request.
Cache Duration
1 hourEach currency pair is cached independently:
USD_INR
USD_EUR
EUR_GBP
GBP_INR🔄 Same Currency Conversion
When the source and target currencies are identical, no API request is made.
const result = await convertCurrency(100, 'USD', 'USD');
console.log(result);
// 100The returned value is rounded to a maximum of four decimal places.
🌐 Currency API
Currency exchange rates are retrieved from the Frankfurter API.
The package requests rates using:
https://api.frankfurter.dev/v2/rate/{from}/{to}For example:
https://api.frankfurter.dev/v2/rate/USD/INRCurrency conversion therefore requires:
- An active internet connection
- Access to the Frankfurter API
- A valid supported currency pair
If the exchange-rate request fails, the function throws an error.
try {
const result = await convertCurrency(100, 'USD', 'INR');
console.log(result);
} catch (error) {
console.error(error);
}💱 Currency Conversion Examples
USD → INR
const result = await convertCurrency(100, 'USD', 'INR');
console.log(result);EUR → USD
const result = await convertCurrency(50, 'EUR', 'USD');
console.log(result);GBP → EUR
const result = await convertCurrency(25, 'GBP', 'EUR');
console.log(result);JPY → INR
const result = await convertCurrency(10000, 'JPY', 'INR');
console.log(result);⚡ Complete Example
import { convertUnit } from 'universal-unit';
const meters = convertUnit({
value: 5,
from: 'km',
to: 'm',
category: 'length',
});
const grams = convertUnit({
value: 5,
from: 'kg',
to: 'g',
category: 'weight',
});
const squareFeet = convertUnit({
value: 100,
from: 'sq_m',
to: 'sq_ft',
category: 'area',
});
const megabytes = convertUnit({
value: 1,
from: 'gb',
to: 'mb',
category: 'data',
});
const minutes = convertUnit({
value: 2,
from: 'hour',
to: 'minute',
category: 'time',
});
console.log(meters);
console.log(grams);
console.log(squareFeet);
console.log(megabytes);
console.log(minutes);📦 Requirements
- Node.js
- npm
- JavaScript or TypeScript
- ES Module support
No external runtime dependencies are required.
🤝 Contributing
Contributions, bug reports, suggestions, and improvements are welcome.
If you would like to contribute:
- Fork the repository.
- Create a new branch.
- Make your changes.
- Test your changes.
- Submit a pull request.
🐛 Issues & Suggestions
Found a bug or have an idea for a new conversion category or unit?
Please open an issue and provide:
- The conversion category
- Source unit
- Target unit
- Expected result
- Actual result
- Relevant code or reproduction steps
📄 License
Universal Unit is released under the MIT License.
You are free to use, modify, distribute, and integrate the package into your projects according to the terms of the MIT License.
⭐ Support
If Universal Unit is useful for your project, consider giving the project a ⭐ and sharing it with other developers.
🌍 Universal Unit
Simple conversions. One API. Zero dependencies.
Built for developers who need a clean and flexible unit conversion utility for JavaScript and TypeScript.
