NHB Toolbox
“I solve problems you face daily”
[!Info] Notice
nhb-toolboxis now split into 3 packages for better maintenance, organization and user experience. It will not receive any new features, only critical bug fixes will be provided in the future updates.
JavaScript/TypeScript Utility Library
NHB Toolbox provides battle-tested utilities for professional JavaScript/TypeScript development. Carefully crafted to solve common challenges with elegant, production-ready solutions:
- Helper Functions & Classes: Reusable solutions for everyday tasks
- Type Guards & Predicates: Runtime safety with perfect type inference
- Validation Utilities: Robust data validation patterns
- Zero Dependencies: Framework-agnostic implementation using only native TS/JS with 0 external package
Installation
Choose your preferred package manager:
npm i nhb-toolboxpnpm add nhb-toolboxyarn add nhb-toolboxChangelog
See Changelog for recent updates.
Key Features
- Type-Safe Utilities:Fully typed for perfect TypeScript integration with strict type checking
- Modular Design: Tree-shaking friendly – import only what you need with zero bloat
- Zero Dependencies: No external dependencies - works with any JS/TS framework
- IDE Support: Full type hints with JSDoc-powered API references in your editor
- Comprehensive Documentation: Learn with real-world use cases on documentation site
- Battle-Tested: Reliable utilities refined through real-world production use
- Optimized for Production: Focused on clean, efficient implementations
Signature Utilities
Date & Time Mastery
Chronos - The ultimate date/time manipulation class with 100+ methods for parsing, formatting, calculating, and comparing dates. Handles all edge cases and timezones safely.
Note: Some methods in
Chronosare available only through the plugin system. This modular design ensures the core bundle stays lightweight — plugins are loaded only when needed, reducing unnecessary code in your final build.
new Chronos('2025-01-01').addDays(3).format('YYYY-MM-DD'); // "2025-01-04"
// or with `Chronos` wrapper
chronos('2025-01-01').addDays(3).format('YYYY-MM-DD'); // "2025-01-04"
Bangla Calendar (Revised: 1966 & 2019)
BanglaCalendar - The class to create, manipulate, and convert dates between the Bangla and Gregorian calendar systems.
It supports two calendar variants:
'revised-2019'(default) and'revised-1966'.
// Create from current date
const today = new BanglaCalendar();
// Create from Bangla date string (Bangla digit)
const date0 = new BanglaCalendar('১৪৩২-১১-০৮');
// Create from Gregorian date
const date1 = new BanglaCalendar('2023-04-14'); // Latin digit
const date2 = new BanglaCalendar(new Date('2023-04-14')); // Date object
// Create with specific Bangla date using Latin digits
const date3 = new BanglaCalendar(1430, 1, 1);
// Create with specific Bangla date using Bangla digits
const date4 = new BanglaCalendar('১৪৩০', '১', '১');
// Create with specific variant
const date5 = new BanglaCalendar('১৪৩০', '১', '১', { variant: 'revised-1966' });
Professional Color Manipulation
Color - Convert between color formats, generate palettes, check accessibility contrast, and perform advanced color math with perfect type safety.
const blue = new Color('#0000ff');
const darkerBlue = blue.applyDarkness(20); // 20% darker
console.log(darkerBlue.hsl); // "hsl(240, 100%, 40%)" (was 50%)
Optimized Array Search
Finder - Blazing-fast array searching with binary search, fuzzy matching, and smart caching. Perfect for large datasets.
const productFinder = new Finder(products);
const laptop = productFinder.findOne('laptop', 'category', {
fuzzy: true,
caseInsensitive: false,
});
Random ID Generation
generateRandomID - Enterprise-grade unique ID generation with prefixes, timestamps, and formatting.
generateRandomID({
prefix: 'user',
timeStamp: true,
length: 12,
caseOption: 'upper',
}); // "USER-171234567890-AB3C4D5E6F7G"
Pluralize Strings and More
pluralizer - Handles English word pluralization and singularization with support for irregular forms and uncountable nouns.
import { pluralizer } from 'nhb-toolbox';
pluralizer.pluralize('child'); // "children"
pluralizer.pluralize('category', { count: 3 }); // "categories"
pluralizer.pluralize('child', { count: 1, inclusive: true }); // "1 child"
pluralizer.toSingular('geese'); // "goose"
pluralizer.toSingular('children'); // "child"
pluralizer.isPlural('children'); // true
pluralizer.isSingular('child'); // true
pluralizer.isPlural('fish'); // true (uncountable)
Color System Utilities
getColorForInitial - Deterministic color mapping system for consistent UI theming
// Get color palette for user avatars
getColorForInitial(['Alice', 'Bob', 'Charlie']);
// ['#00094C', '#00376E', '#005600']
getColorForInitial('Banana', 50); // '#00376E80' (50% opacity)
FormData Preparation
createFormData - Convert JavaScript objects into FormData with extensive configuration options for handling nested structures, files, and data transformations.
import { createFormData } from 'nhb-toolbox';
const data = {
user: {
name: ' John Doe ',
age: 30,
preferences: { theme: 'dark' }
},
files: [file1, file2]
};
const formData = createFormData(data, {
trimStrings: true,
lowerCaseValues: ['user.name'],
dotNotateNested: ['user'],
breakArray: ['files']
});
// Resulting FormData:
// user.name=john doe
// user.age=30
// user.preferences.theme=dark
// files[0]=[File1]
// files[1]=[File2]
Data Sanitization
sanitizeData - Clean and normalize strings/objects by trimming whitespace, removing empty values, and applying customizable filters.
const user = {
name: ' John Doe ',
age: null,
address: { city: ' NYC ', zip: '' },
tags: [],
};
sanitizeData(user, { ignoreFalsy: true, ignoreEmpty: true });
// Returns { name: "John Doe", address: { city: "NYC" } } with exact input type which may cause issue when accessing missing properties
sanitizeData(user, { ignoreFalsy: true, ignoreEmpty: true }, 'partial');
// Return type: $DeepPartial<typeof user> safe property access by making all the properties (nested objects/arrays) optional
// Returns { name: "John Doe", address: { city: "NYC" } }
JSON Hydration
parseJSON - Bulletproof JSON parsing with primitive conversion
parseJSON('{"value":"42"}'); // { value: 42 } (auto-converts numbers)
Number to Words
numberToWords - Convert numbers to human-readable words (supports up to 100 quintillion).
numberToWords(125); // "one hundred twenty-five"
Advanced Number Operations
getNumbersInRange - Generate intelligent number sequences with prime, even/odd, and custom filtering capabilities
// Get primes between 10-30 as formatted string
getNumbersInRange('prime', { min: 10, max: 30, getAsString: true });
// "11, 13, 17, 19, 23, 29"
calculatePercentage - Swiss Army knife for percentage calculations with 7 specialized modes
// Calculate percentage change
calculatePercentage({
mode: 'get-change-percent',
oldValue: 100,
newValue: 150,
}); // 50 (50% increase)
Extract Updated Fields
extractUpdatedFields - Detect exactly what changed between two objects (including deep nested changes).
const dbRecord = { id: 1, content: 'Hello', meta: { views: 0 } };
const update = { content: 'Hello', meta: { views: 1 } };
extractUpdatedFields(dbRecord, update);
// { meta: { views: 1 } }
Style Console Output(s)
Stylog - Chalk-like minimal utility to style console output(s) in both Node.js & Browser environment(s) (supports named CSS colors).
// Basic coloring
Stylog.error.log('Error message');
Stylog.success.log('Success message');
Stylog.info.log('Info message');
Stylog.whitesmoke.log('I am White!');
// Multiple styles
Stylog.blue.bold.underline.log('I am Bold Underlined Blue!');
// With object stringification
Stylog.magenta.italic.log({ data: 'value' }, true);
Performance Optimizers
throttleAction - Precision control for high-frequency events
// Smooth scroll handling
throttleAction(updateScrollPosition, 100);
debounceAction - Intelligent delay for expensive operations
// Search-as-you-type
debounceAction(fetchResults, 300);
These utilities represent just a portion of the comprehensive
nhb-toolbox. Each is designed with production-grade reliability and developer experience in mind. Explore more in the full documentation. All the utilities and classes are categorized.
Related Packages
License
This project is licensed under the Apache License 2.0 with the following additional requirement:
Additional Requirement:
Any fork, derivative work, or redistribution of this project must include clear attribution to Nazmul Hassan in both the source code and any publicly available documentation.
You are free to use, modify, and distribute this project under the terms of the Apache 2.0 License, provided that appropriate credit is given.
Built with by Nazmul Hassan