@julian-i/try-utils
v0.1.2
Published
A collection of utility functions with comprehensive error handling, using the @julian-i/try-error pattern.
Maintainers
Readme
@julian-i/try-utils
A comprehensive collection of utility functions with robust error handling, built with TypeScript and inspired by functional programming principles.
Features
- Comprehensive Error Handling: All utilities use tuple-based error handling with
[result, error]pattern - TypeScript First: Full TypeScript support with excellent type inference
- Zero Dependencies: Minimal external dependencies for maximum compatibility
- Extensive Testing: Thorough test coverage for all edge cases and error scenarios
- Modular Design: Import only what you need to keep bundle size minimal
Installation
npm install @julian-i/try-utilsUsage
String Utilities
import {
capitalize,
camelCase,
snakeCase,
truncate,
} from "@julian-i/try-utils";
// Basic usage
const [result, error] = capitalize("hello world");
if (error) {
console.error("Error:", error.message);
} else {
console.log(result); // "Hello world"
}
// Case conversion
const [camel, _] = camelCase("hello_world"); // "helloWorld"
const [snake, __] = snakeCase("helloWorld"); // "hello_world"
// Truncation with custom suffix
const [truncated, ___] = truncate("This is a very long string", 10, "...");
// "This is..."Number Utilities
import {
validateNumber,
formatNumber,
randomInt,
factorial,
isPrime,
} from "@julian-i/try-utils";
// Validation
const [num, error] = validateNumber("123", { min: 0, max: 1000 });
if (error) {
console.error("Invalid number:", error.message);
}
// Formatting
const [formatted, _] = formatNumber(1234.56, {
decimals: 2,
currency: "USD",
}); // "$1,234.56"
// Math operations
const [fact, __] = factorial(5); // 120
const [isPrimeNum, ___] = isPrime(17); // true
const [random, ____] = randomInt(1, 100); // Random number between 1-100Fetch Utilities
import { safeFetch } from "@julian-i/try-utils";
// Safe fetch with error handling
const [data, error] = await safeFetch("https://api.example.com/data", {});
if (error) {
console.error("Fetch failed:", error.message);
} else {
console.log("Fetched data:", data);
}API Reference
String Utilities
capitalize(str, options?)- Capitalize first letter, lowercase restcamelCase(str, options?)- Convert to camelCasesnakeCase(str, options?)- Convert to snake_casekebabCase(str, options?)- Convert to kebab-casepascalCase(str, options?)- Convert to PascalCasetitleCase(str, options?)- Convert to Title Casetruncate(str, maxLength, suffix?, options?)- Truncate string with suffixreverse(str, options?)- Reverse stringcountWords(str, options?)- Count words in stringremoveExtraSpaces(str, options?)- Remove extra whitespaceisPalindrome(str, options?)- Check if string is palindrome
Number Utilities
validateNumber(value, options?)- Validate and parse numberformatNumber(num, options?)- Format number with locale/currencyrandomInt(min, max)- Generate random integerrandomFloat(min, max, decimals?)- Generate random floatfactorial(n)- Calculate factorialfibonacci(n)- Generate Fibonacci sequenceisPrime(n)- Check if number is primegcd(a, b)- Greatest common divisorlcm(a, b)- Least common multiplesum(numbers)- Sum array of numbersaverage(numbers)- Calculate averagemin(numbers)- Find minimum valuemax(numbers)- Find maximum valueclamp(value, min, max)- Clamp value between min and maxroundToDecimal(num, decimals)- Round to specific decimal places
Fetch Utilities
safeFetch(url, options?)- Safe fetch with error handling
Error Handling
All utilities return a tuple [result, error] where:
resultis the successful value (ornullif error)erroris an Error object (ornullif successful)
const [result, error] = someUtility(input);
if (error) {
// Handle error
console.error(error.message);
} else {
// Use result
console.log(result);
}Validation Options
String Validation
interface StringValidationOptions {
maxLength?: number; // Maximum string length
allowWhitespaceOnly?: boolean; // Allow strings with only whitespace
allowSpecialChars?: boolean; // Allow special characters
}Number Validation
interface NumberValidationOptions {
min?: number; // Minimum value
max?: number; // Maximum value
allowDecimals?: boolean; // Allow decimal numbers
allowNegative?: boolean; // Allow negative numbers
allowZero?: boolean; // Allow zero
}Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run tests:
bun run test:run - Submit a pull request
License
MIT
