@teknyo/unit-converter
v1.0.0
Published
A simple and lightweight unit converter for JavaScript and TypeScript
Maintainers
Readme
Simple Unit Converter
A lightweight, type-safe unit converter for JavaScript and TypeScript supporting length, weight, temperature, volume, and area conversions.
Features
- 🚀 Lightweight - Minimal dependencies, small bundle size
- 🔥 TypeScript Support - Full type safety and IntelliSense
- 📦 Multiple Formats - CommonJS, ES Modules, and UMD
- 🧪 Well Tested - Comprehensive test coverage
- 🌍 Universal - Works in Node.js and browsers
- 📏 Multiple Categories - Length, weight, temperature, volume, and area
Installation
npm install @teknyo/unit-converteryarn add @teknyo/unit-converterQuick Start
// ES Modules
import { convert } from '@teknyo/unit-converter';
// CommonJS
const { convert } = require('@teknyo/unit-converter');
// Basic conversion
const result = convert(100, 'cm', 'm');
console.log(result); // { value: 1, from: 'cm', to: 'm', category: 'length' }
// Temperature conversion
const temp = convert(32, 'F', 'C');
console.log(temp.value); // 0
// Weight conversion
const weight = convert(1000, 'g', 'kg');
console.log(weight.value); // 1Supported Units
Length
- Metric:
mm,cm,m,km - Imperial:
in,ft,yd,mi
Weight
- Metric:
mg,g,kg,t(metric ton) - Imperial:
oz,lb,st(stone)
Temperature
C(Celsius),F(Fahrenheit),K(Kelvin)
Volume
- Metric:
ml,l,kl - US Customary:
tsp,tbsp,cup,pt,qt,gal
Area
- Metric:
mm2,cm2,m2,km2,ha(hectare) - Imperial:
in2,ft2,yd2,ac(acre),mi2
API Reference
convert(value, from, to, options?)
Main conversion function.
const result = convert(value: number, from: Unit, to: Unit, options?: ConversionOptions);Parameters:
value- The numeric value to convertfrom- Source unitto- Target unitoptions- Optional conversion settings
Options:
interface ConversionOptions {
precision?: number; // Decimal places (default: 10)
round?: boolean; // Whether to round result (default: true)
}Returns:
interface ConversionResult {
value: number;
from: Unit;
to: Unit;
category: UnitCategory;
}Utility Functions
getUnitInfo(unit)
Get detailed information about a unit:
import { getUnitInfo } from 'simple-unit-converter';
const info = getUnitInfo('m');
console.log(info);
// {
// unit: 'm',
// category: 'length',
// name: 'Meter',
// symbol: 'm',
// baseUnit: true
// }isValidUnit(unit)
Check if a unit is supported:
import { isValidUnit } from 'simple-unit-converter';
console.log(isValidUnit('m')); // true
console.log(isValidUnit('xyz')); // falsegetSupportedCategories()
Get all available unit categories:
import { getSupportedCategories } from 'simple-unit-converter';
console.log(getSupportedCategories());
// ['length', 'weight', 'temperature', 'volume', 'area']getUnitsForCategory(category)
Get all units for a specific category:
import { getUnitsForCategory } from 'simple-unit-converter';
console.log(getUnitsForCategory('length'));
// ['mm', 'cm', 'm', 'km', 'in', 'ft', 'yd', 'mi']areUnitsCompatible(unit1, unit2)
Check if two units can be converted between each other:
import { areUnitsCompatible } from 'simple-unit-converter';
console.log(areUnitsCompatible('m', 'ft')); // true (both length)
console.log(areUnitsCompatible('m', 'kg')); // false (different categories)Examples
Basic Conversions
import { convert } from 'simple-unit-converter';
// Length
convert(1, 'km', 'm'); // { value: 1000, from: 'km', to: 'm', category: 'length' }
convert(12, 'in', 'cm'); // { value: 30.48, from: 'in', to: 'cm', category: 'length' }
// Weight
convert(2.5, 'kg', 'lb'); // { value: 5.5115565546, from: 'kg', to: 'lb', category: 'weight' }
// Temperature
convert(100, 'C', 'F'); // { value: 212, from: 'C', to: 'F', category: 'temperature' }
convert(273.15, 'K', 'C'); // { value: 0, from: 'K', to: 'C', category: 'temperature' }
// Volume
convert(1, 'gal', 'l'); // { value: 3.78541, from: 'gal', to: 'l', category: 'volume' }
// Area
convert(1, 'ac', 'm2'); // { value: 4046.86, from: 'ac', to: 'm2', category: 'area' }With Options
import { convert } from 'simple-unit-converter';
// High precision
const precise = convert(1, 'in', 'mm', { precision: 6 });
console.log(precise.value); // 25.4
// Custom precision
const rounded = convert(1, 'kg', 'lb', { precision: 2 });
console.log(rounded.value); // 2.2
// No rounding
const exact = convert(1, 'mi', 'km', { precision: 10, round: false });
console.log(exact.value); // 1.609344Error Handling
import { convert } from 'simple-unit-converter';
try {
// This will throw an error - incompatible categories
convert(100, 'm', 'kg');
} catch (error) {
console.error(error.message);
// "Cannot convert between different categories: length and weight"
}
try {
// This will throw an error - unsupported unit
convert(100, 'xyz', 'm');
} catch (error) {
console.error(error.message);
// "Unsupported unit: xyz"
}Building a Conversion Tool
import {
convert,
getSupportedCategories,
getUnitsForCategory,
getUnitInfo
} from 'simple-unit-converter';
// Get all categories
const categories = getSupportedCategories();
// Build a conversion interface
categories.forEach(category => {
console.log(`\n${category.toUpperCase()}`);
const units = getUnitsForCategory(category);
units.forEach(unit => {
const info = getUnitInfo(unit);
console.log(` ${unit} - ${info.name} (${info.symbol})`);
});
});
// Example conversion with validation
function safeConvert(value, from, to) {
try {
const result = convert(value, from, to);
return {
success: true,
result: result
};
} catch (error) {
return {
success: false,
error: error.message
};
}
}
const conversion = safeConvert(100, 'cm', 'm');
if (conversion.success) {
console.log(`Result: ${conversion.result.value}`);
} else {
console.error(`Error: ${conversion.error}`);
}TypeScript Support
The package is written in TypeScript and provides full type safety:
import { convert, Unit, UnitCategory, ConversionResult } from 'simple-unit-converter';
// Type-safe unit parameters
const from: Unit = 'm';
const to: Unit = 'ft';
// Type-safe result
const result: ConversionResult = convert(100, from, to);
// IntelliSense will show available units
const temp = convert(32, 'F', 'C'); // 'F' and 'C' are suggestedLicense
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
1.0.0
- Initial release
- Support for length, weight, temperature, volume, and area conversions
- TypeScript support
- Comprehensive test coverage
- Multiple output formats (CommonJS, ES Modules)
