@hphudev/utils
v2.0.4
Published
Common utility functions in JS/TS
Maintainers
Readme
@hphudev/utils
The @hphudev/utils package is a TypeScript utility library designed for common data manipulation tasks. It provides five main classes—StringHandler, NumberHandler, ImageHandler, ObjectHandler, and DateTimeHandler—each offering a comprehensive set of static methods for string transformation, number operations, image processing, object manipulation, and date-time handling. This package is ideal for web development, data processing, API integration, and UI applications, featuring zero dependencies and full TypeScript support
Installation
To install the @hphudev/utils package, run the following command:
npm install @hphudev/utilsEnsure you have TypeScript installed in your project if you are using it. For JavaScript projects, the package is compatible with ES modules and CommonJS.
Usage
The StringHandler, NumberHandler, ObjectHandler, ImageHandler, and DateTimeHandler classes contain static methods, so you don't need to instantiate them. Simply import the classes and call the methods directly.
Example
import { StringHandler, NumberHandler, ObjectHandler, ImageHandler, DateTimeHandler } from '@hphudev/utils';
// StringHandler example
console.log(StringHandler.capitalize("hello")); // Output: "Hello"
console.log(StringHandler.isEmail("[email protected]")); // Output: true
console.log(StringHandler.slugify("Hello World!")); // Output: "hello-world"
// NumberHandler example
console.log(NumberHandler.isPrime(17)); // Output: true
console.log(NumberHandler.formatCurrency(1234.56)); // Output: "$1,234.56"
console.log(NumberHandler.randomInt(1, 10)); // Output: e.g., 7
// ObjectHandler example
console.log(ObjectHandler.toCamelCaseKeys({ first_name: "John", last_name: "Doe" })); // Output: { firstName: "John", lastName: "Doe" }
console.log(ObjectHandler.isNonEmptyObject({ key: "value" })); // Output: true
console.log(ObjectHandler.omitKeys({ a: 1, b: 2, c: 3 }, ['b'])); // Output: { a: 1, c: 3 }
// ImageHandler example (Note: These are async methods)
async function imageExamples() {
const base64Image = "data:image/png;base64,iVBORw0KGgo..."; // Example base64 image
console.log(await ImageHandler.resizeImage(base64Image, 100, 100)); // Output: Base64 string of resized image
console.log(await ImageHandler.toGrayscale(base64Image)); // Output: Base64 string of grayscale image
console.log(await ImageHandler.getDimensions(base64Image)); // Output: { width: 1920, height: 1080 } (example dimensions)
}
// DateTimeHandler example
console.log(DateTimeHandler.formatDate(new Date('2025-07-25'), 'YYYY-MM-DD')); // Output: "2025-07-25"
console.log(DateTimeHandler.isToday(new Date('2025-07-25'))); // Output: true (if today is 2025-07-25)
console.log(DateTimeHandler.diffInDays(new Date('2025-07-25'), new Date('2025-07-20'))); // Output: 5StringHandler
The StringHandler class provides a collection of static methods for string manipulation, validation, analysis, extraction, and generation.
String Transformation
capitalize(str: string): stringCapitalizes the first letter of a string. Example :StringHandler.capitalize("hello")→"Hello"slugify(str: string): stringConverts a string into a URL-friendly slug. Example :StringHandler.slugify("Xin Chào bạn ơi!")→"xin-chao-ban-oi"toCamelCase(str: string): stringConverts a string to camelCase. Example :StringHandler.toCamelCase("hello-world")→"helloWorld"toSnakeCase(str: string): stringConverts a string to snake_case. Example :StringHandler.toSnakeCase("helloWorld")→"hello_world"toKebabCase(str: string): stringConverts a string to kebab-case. Example :StringHandler.toKebabCase("helloWorld")→"hello-world"toPascalCase(str: string): stringConverts a string to PascalCase. Example :StringHandler.toPascalCase("hello-world")→"HelloWorld"toTitleCase(str: string): stringConverts a string to title case. Example :StringHandler.toTitleCase("hello world")→"Hello World"toSentenceCase(str: string): stringConverts a string to sentence case. Example :StringHandler.toSentenceCase("hello WORLD")→"Hello world"toHyphenated(str: string): stringConverts a string to hyphenated lowercase. Example :StringHandler.toHyphenated("Hello World")→"hello-world"toCustomSlug(str: string, separator: string = '-'): stringCreates a slug with a custom separator. Example :StringHandler.toCustomSlug("Hello World", "_")→"hello_world"toLimitedKebabCase(str: string, maxLength: number = 50): stringConverts to kebab-case with a length limit. Example :StringHandler.toLimitedKebabCase("Hello World Example", 10)→"hello-world"toLocaleUpperCase(str: string, locale: string = 'en-US'): stringConverts to uppercase with locale support. Example :StringHandler.toLocaleUpperCase("hello")→"HELLO"toLocaleLowerCase(str: string, locale: string = 'en-US'): stringConverts to lowercase with locale support. Example :StringHandler.toLocaleLowerCase("HELLO")→"hello"toBase64(str: string): stringEncodes to Base64. Example :StringHandler.toBase64("hello")→"aGVsbG8="fromBase64(str: string): stringDecodes from Base64. Example :StringHandler.fromBase64("aGVsbG8=")→"hello"normalize(str: string): stringRemoves diacritics from a string. Example :StringHandler.normalize("Héllô Wørld")→"Hello World"truncate(str: string, length: number, ending: string = '...'): stringTruncates a string if it exceeds the specified length. Example :StringHandler.truncate("Hello world", 5)→"He..."truncateWords(str: string, maxWords: number, ending: string = '...'): stringTruncates to a specified number of words. Example :StringHandler.truncateWords("Hello world this is a test", 3)→"Hello world this..."reverse(str: string): stringReverses the characters of a string. Example :StringHandler.reverse("hello")→"olleh"capitalizeWords(str: string): stringCapitalizes the first letter of each word. Example :StringHandler.capitalizeWords("hello world")→"Hello World"capitalizeSentences(str: string): stringCapitalizes the first letter of each sentence. Example :StringHandler.capitalizeSentences("hello. world!")→"Hello. World!"removeWhitespace(str: string): stringRemoves all whitespace characters. Example :StringHandler.removeWhitespace(" hello world ")→"helloworld"removeSpecialCharacters(str: string): stringRemoves special characters, keeping alphanumerics and spaces. Example :StringHandler.removeSpecialCharacters("Hello! @World#")→"Hello World"keepAlphanumeric(str: string): stringRemoves non-alphanumeric characters. Example :StringHandler.keepAlphanumeric("Hello!@123")→"Hello123"trimChars(str: string, chars: string = ' '): stringTrims specific characters from both ends. Example :StringHandler.trimChars("##hello##", "#")→"hello"repeat(str: string, times: number): stringRepeats a string a specified number of times. Example :StringHandler.repeat("abc", 3)→"abcabcabc"removeDuplicates(str: string): stringRemoves duplicate characters. Example :StringHandler.removeDuplicates("hello")→"helo"deduplicateChar(str: string, char: string): stringReplaces multiple consecutive occurrences of a character with a single one. Example :StringHandler.deduplicateChar("hello----world", "-")→"hello-world"toSafeFilePath(str: string): stringSanitizes a string for safe use in file paths. Example :StringHandler.toSafeFilePath("My:Doc/ument.txt")→"My_Document.txt"urlEncode(str: string): stringConverts to URL-encoded format. Example :StringHandler.urlEncode("hello world!")→"hello%20world%21"urlDecode(str: string): stringDecodes a URL-encoded string. Example :StringHandler.urlDecode("hello%20world%21")→"hello world!"escapeHtml(str: string): stringEscapes HTML special characters. Example :StringHandler.escapeHtml("<p>Hello & World</p>")→"<p>Hello & World</p>"unescapeHtml(str: string): stringUnescapes HTML entities. Example :StringHandler.unescapeHtml("<p>Hello & World</p>")→"<p>Hello & World</p>"stripHtml(str: string): stringRemoves HTML tags. Example :StringHandler.stripHtml("<p>Hello</p>")→"Hello"toQueryString(str: string): stringConverts a string to a URL query string. Example :StringHandler.toQueryString("name=John&age=30")→"name=John&age=30"formatString(str: string, ...args: string[]): stringFormats a string by replacing placeholders. Example :StringHandler.formatString("Hello, {0}!", "World")→"Hello, World!"formatPhoneNumber(str: string, format: string): stringFormats a phone number according to a template. Example :StringHandler.formatPhoneNumber("1234567890", "(###) ###-####")→"(123) 456-7890"toCurrency(str: string, currency: string = 'USD', locale: string = 'en-US'): stringConverts a numeric string to a formatted currency string. Example :StringHandler.toCurrency("1234.56")→"$1,234.56"toReadableDate(str: string): stringConverts an ISO date string to a readable format. Example :StringHandler.toReadableDate("2025-07-25")→"July 25, 2025"toFileSize(str: string): stringConverts a numeric string (bytes) to a human-readable file size. Example :StringHandler.toFileSize("1048576")→"1 MB"padLeft(str: string, length: number, padChar: string = ' '): stringPads a string with a character on the left. Example :StringHandler.padLeft("123", 5, "0")→"00123"padRight(str: string, length: number, padChar: string = ' '): stringPads a string with a character on the right. Example :StringHandler.padRight("123", 5, "0")→"12300"mask(str: string, start: number, length: number, maskChar: string = '*'): stringMasks a portion of a string. Example :StringHandler.mask("1234567890", 4, 4)→"1234****90"removeLeadingZeros(str: string): stringRemoves leading zeros from a numeric string. Example :StringHandler.removeLeadingZeros("00123")→"123"
String Validation
isEmail(str: string): booleanChecks if a string is a valid email address. Example :StringHandler.isEmail("[email protected]")→trueisUrl(str: string): booleanValidates if a string is a valid URL. Example :StringHandler.isUrl("https://example.com")→trueisUUID(str: string): booleanValidates if a string is a valid UUID v4. Example :StringHandler.isUUID("550e8400-e29b-41d4-a716-446655440000")→trueisAnyUUID(str: string): booleanChecks if a string is a valid UUID (any version). Example :StringHandler.isAnyUUID("123e4567-e89b-12d3-a456-426614174000")→trueisVietnamesePhone(str: string): booleanValidates a Vietnamese phone number. Example :StringHandler.isVietnamesePhone("0901234567")→trueisValidDate(str: string): booleanChecks if a string is a valid ISO date (YYYY-MM-DD). Example :StringHandler.isValidDate("2025-07-25")→trueisBlank(str: string): booleanChecks if a string is empty or contains only whitespace. Example :StringHandler.isBlank(" ")→trueisNumeric(str: string): booleanChecks if a string contains only digits. Example :StringHandler.isNumeric("123")→trueisAlphabetic(str: string): booleanChecks if a string contains only alphabetic characters. Example :StringHandler.isAlphabetic("Hello")→trueisAlphanumeric(str: string): booleanChecks if a string contains only alphanumeric characters. Example :StringHandler.isAlphanumeric("Hello123")→trueisHex(str: string): booleanChecks if a string is a valid hexadecimal string. Example :StringHandler.isHex("1a2b3c")→trueisHexColor(str: string): booleanChecks if a string is a valid hexadecimal color code. Example :StringHandler.isHexColor("#FF0000")→trueisCssColor(str: string): booleanChecks if a string is a valid CSS color name. Example :StringHandler.isCssColor("red")→trueisIPv4(str: string): booleanChecks if a string is a valid IPv4 address. Example :StringHandler.isIPv4("192.168.1.1")→trueisMacAddress(str: string): booleanChecks if a string is a valid MAC address. Example :StringHandler.isMacAddress("00:1A:2B:3C:4D:5E")→trueisIsbn(str: string): booleanChecks if a string is a valid ISBN-10 or ISBN-13. Example :StringHandler.isIsbn("978-3-16-148410-0")→trueisValidPassword(str: string, minLength: number = 8, requireSpecial: boolean = true): booleanChecks if a string meets password requirements. Example :StringHandler.isValidPassword("Password123!")→trueisInternationalPhone(str: string): booleanValidates an international phone number. Example :StringHandler.isInternationalPhone("+12025550123")→trueisJson(str: string): booleanChecks if a string is valid JSON. Example :StringHandler.isJson('{"key": "value"}')→trueisMongoId(str: string): booleanChecks if a string is a valid MongoDB ObjectId. Example :StringHandler.isMongoId("507f1f77bcf86cd799439011")→trueisJwt(str: string): booleanChecks if a string is a valid JWT token format. Example :StringHandler.isJwt("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dummysig")→trueisBase64Image(str: string): booleanChecks if a string is a valid base64-encoded image. Example :StringHandler.isBase64Image("data:image/png;base64,iVBORw0KGgo=")→trueisTime(str: string): booleanChecks if a string is a valid time in HH:MM or HH:MM:SS format. Example :StringHandler.isTime("14:30")→trueisPostalCode(str: string, countryCode: string = 'US'): booleanValidates a postal code for a given country. Example :StringHandler.isPostalCode("90210", "US")→trueisValidFileName(str: string): booleanChecks if a string is a valid file name. Example :StringHandler.isValidFileName("document.txt")→trueisPrintableAscii(str: string): booleanChecks if a string contains only printable ASCII characters. Example :StringHandler.isPrintableAscii("Hello123!")→trueisDomain(str: string): booleanValidates if a string is a valid domain name. Example :StringHandler.isDomain("example.com")→trueisSlug(str: string): booleanValidates if a string is a valid slug. Example :StringHandler.isSlug("hello-world")→true
String Analysis
countOccurrences(str: string, searchStr: string): numberCounts occurrences of a substring. Example :StringHandler.countOccurrences("hello hello", "hello")→2isPalindrome(str: string): booleanChecks if a string is a palindrome. Example :StringHandler.isPalindrome("racecar")→trueisAnagram(str1: string, str2: string): booleanChecks if two strings are anagrams. Example :StringHandler.isAnagram("listen", "silent")→truecontains(str: string, substring: string): booleanChecks if a string contains a substring. Example :StringHandler.contains("Hello world", "world")→truestartsWith(str: string, prefix: string): booleanChecks if a string starts with a prefix. Example :StringHandler.startsWith("Hello world", "Hello")→trueendsWith(str: string, suffix: string): booleanChecks if a string ends with a suffix. Example :StringHandler.endsWith("Hello world", "world")→truehasEmoji(str: string): booleanChecks if a string contains emojis. Example :StringHandler.hasEmoji("Hello 😊")→trueisBalancedParentheses(str: string): booleanChecks if a string has balanced parentheses. Example :StringHandler.isBalancedParentheses("(hello (world))")→truematches(str: string, regex: RegExp): booleanChecks if a string matches a regular expression. Example :StringHandler.matches("hello123", /^[a-z0-9]+$/i)→truematchesAny(str: string, patterns: RegExp[]): booleanChecks if a string matches any of the provided regex patterns. Example :StringHandler.matchesAny("hello123", [/^[a-z0-9]+$/, /^\d+$/])→truehashCode(str: string): numberGenerates a numeric hash code for a string. Example :StringHandler.hashCode("hello")→99162322
String Extraction
extractNumbers(str: string): stringExtracts all digits from a string. Example :StringHandler.extractNumbers("abc123def456")→"123456"extractEmails(str: string): string[]Extracts all email addresses from a string. Example :StringHandler.extractEmails("Contact: [email protected], [email protected]")→["[email protected]", "[email protected]"]extractDomain(str: string): stringExtracts the domain from a URL. Example :StringHandler.extractDomain("https://example.com/path")→"example.com"getFileExtension(str: string): stringExtracts the file extension from a file name. Example :StringHandler.getFileExtension("document.pdf")→"pdf"
String Generation
randomString(length: number = 8): stringGenerates a random alphanumeric string. Example :StringHandler.randomString(6)→"A1b2Cd"randomLowercase(length: number = 8): stringGenerates a random lowercase string. Example :StringHandler.randomLowercase(6)→"abcdef"randomUppercase(length: number = 8): stringGenerates a random uppercase string. Example :StringHandler.randomUppercase(6)→"ABCDEF"generatePattern(pattern: string): stringGenerates a random string based on a pattern. Example :StringHandler.generatePattern("xxx-###")→"abc-123"
Miscellaneous
toNumber(str: string, defaultValue: number = 0): numberConverts a string to a number. Example :StringHandler.toNumber("123.45")→123.45toBoolean(str: string): booleanConverts a string to a boolean. Example :StringHandler.toBoolean("true")→truechunk(str: string, chunkSize: number): string[]Splits a string into chunks. Example :StringHandler.chunk("hello", 2)→["he", "ll", "o"]toWords(str: string): string[]Splits a string into words. Example :StringHandler.toWords("Hello, world!")→["Hello", "world"]toLines(str: string): string[]Splits a string into non-empty lines. Example :StringHandler.toLines("Hello\nWorld")→["Hello", "World"]isWhitespaceOr(str: string, allowedChars: string = ''): booleanChecks if a string contains only whitespace or allowed characters. Example :StringHandler.isWhitespaceOr(" \t\n", "\t\n")→truereplaceAll(str: string, search: string, replacement: string): stringReplaces all occurrences of a substring. Example :StringHandler.replaceAll("Hello hello", "hello", "world")→"Hello world"
NumberHandler
The NumberHandler class provides static methods for number validation, manipulation, formatting, statistical operations, random number generation, and trigonometric/geometric calculations.
Number Validation
isValidNumber(value: any): booleanChecks if a value is a valid number. Example :NumberHandler.isValidNumber(123)→trueisInteger(value: any): booleanChecks if a value is an integer. Example :NumberHandler.isInteger(5)→trueisEven(value: number): booleanChecks if a number is even. Example :NumberHandler.isEven(4)→trueisOdd(value: number): booleanChecks if a number is odd. Example :NumberHandler.isOdd(5)→trueisPositive(value: number): booleanChecks if a number is positive. Example :NumberHandler.isPositive(5)→trueisNegative(value: number): booleanChecks if a number is negative. Example :NumberHandler.isNegative(-5)→trueisZero(value: number): booleanChecks if a number is zero. Example :NumberHandler.isZero(0)→trueisInRange(value: number, min: number, max: number): booleanChecks if a number is within a range. Example :NumberHandler.isInRange(5, 1, 10)→trueisPrime(value: number): booleanChecks if a number is prime. Example :NumberHandler.isPrime(17)→trueisPerfectSquare(value: number): booleanChecks if a number is a perfect square. Example :NumberHandler.isPerfectSquare(16)→trueisPowerOfTwo(value: number): booleanChecks if a number is a power of two. Example :NumberHandler.isPowerOfTwo(8)→trueisTriangular(value: number): booleanChecks if a number is triangular. Example :NumberHandler.isTriangular(6)→trueisPalindrome(value: number): booleanChecks if a number is a palindrome. Example :NumberHandler.isPalindrome(12321)→trueisPerfectNumber(value: number): booleanChecks if a number is perfect. Example :NumberHandler.isPerfectNumber(6)→trueisFibonacci(value: number): booleanChecks if a number is a Fibonacci number. Example :NumberHandler.isFibonacci(8)→trueisArmstrong(value: number): booleanChecks if a number is an Armstrong number. Example :NumberHandler.isArmstrong(153)→trueisMultiple(value: number, divisor: number): booleanChecks if a number is a multiple of another. Example :NumberHandler.isMultiple(15, 5)→trueisPowerOf(value: number, base: number): booleanChecks if a number is a power of a given base. Example :NumberHandler.isPowerOf(16, 2)→trueisWithinTolerance(value: number, target: number, tolerance: number): booleanChecks if a number is within a tolerance of a target. Example :NumberHandler.isWithinTolerance(10.1, 10, 0.5)→trueapproxEqual(a: number, b: number, epsilon: number): booleanChecks if two numbers are approximately equal. Example :NumberHandler.approxEqual(1.0000001, 1, 0.0001)→trueisHappy(value: number): booleanChecks if a number is happy. Example :NumberHandler.isHappy(19)→true
Number Manipulation
abs(value: number): numberReturns the absolute value. Example :NumberHandler.abs(-10)→10pow(base: number, exponent: number): numberCalculates the power of a number. Example :NumberHandler.pow(2, 3)→8sqrt(value: number): numberCalculates the square root. Example :NumberHandler.sqrt(16)→4nthRoot(value: number, n: number): numberCalculates the nth root. Example :NumberHandler.nthRoot(8, 3)→2clamp(value: number, min: number, max: number): numberClamps a number between a minimum and maximum. Example :NumberHandler.clamp(10, 0, 5)→5clampToInt(value: number, min: number, max: number): numberClamps a number to an integer within a range. Example :NumberHandler.clampToInt(5.7, 0, 5)→5roundTo(value: number, decimals: number): numberRounds to a specified number of decimal places. Example :NumberHandler.roundTo(3.14159, 2)→3.14truncate(value: number, decimals: number): numberTruncates to a specified number of decimal places. Example :NumberHandler.truncate(3.14159, 2)→3.14roundToNearest(value: number, multiple: number): numberRounds to the nearest multiple. Example :NumberHandler.roundToNearest(17, 5)→15roundToEven(value: number): numberRounds to the nearest even integer. Example :NumberHandler.roundToEven(3.7)→4ceil(value: number): numberRounds up to the nearest integer. Example :NumberHandler.ceil(3.14)→4floor(value: number): numberRounds down to the nearest integer. Example :NumberHandler.floor(3.86)→3mod(value: number, divisor: number): numberCalculates modulo with a non-negative result. Example :NumberHandler.mod(-7, 3)→2factorial(value: number): numberCalculates the factorial. Example :NumberHandler.factorial(5)→120fibonacci(n: number): numberCalculates the nth Fibonacci number. Example :NumberHandler.fibonacci(6)→8lerp(start: number, end: number, t: number): numberLinearly interpolates between two numbers. Example :NumberHandler.lerp(0, 100, 0.5)→50normalize(value: number, oldMin: number, oldMax: number, newMin: number, newMax: number): numberNormalizes a number to a new range. Example :NumberHandler.normalize(50, 0, 100, 0, 1)→0.5gcd(a: number, b: number): numberCalculates the greatest common divisor. Example :NumberHandler.gcd(48, 18)→6lcm(a: number, b: number): numberCalculates the least common multiple. Example :NumberHandler.lcm(12, 18)→36gcdArray(numbers: number[]): numberCalculates the GCD of an array. Example :NumberHandler.gcdArray([48, 18, 12])→6lcmArray(numbers: number[]): numberCalculates the LCM of an array. Example :NumberHandler.lcmArray([12, 18])→36sumOfDigits(value: number): numberCalculates the sum of digits. Example :NumberHandler.sumOfDigits(123)→6reverseDigits(value: number): numberReverses the digits of a number. Example :NumberHandler.reverseDigits(123)→321countDigits(value: number): numberCounts the number of digits. Example :NumberHandler.countDigits(12345)→5nextPower(value: number, base: number): numberFinds the next power of a base. Example :NumberHandler.nextPower(10, 2)→16absoluteDifference(a: number, b: number): numberCalculates the absolute difference. Example :NumberHandler.absoluteDifference(10, 7)→3
Number Formatting
toPercentage(value: number, decimals: number): stringConverts to a percentage string. Example :NumberHandler.toPercentage(0.875, 1)→"87.5%"formatWithCommas(value: number): stringAdds thousand separators. Example :NumberHandler.formatWithCommas(1000000)→"1,000,000"formatCurrency(value: number, currency: string, locale: string): stringFormats as currency. Example :NumberHandler.formatCurrency(1234.56)→"$1,234.56"toScientific(value: number, decimals: number): stringFormats in scientific notation. Example :NumberHandler.toScientific(12345, 2)→"1.23e+4"padWithZeros(value: number, length: number): stringPads with leading zeros. Example :NumberHandler.padWithZeros(7, 3)→"007"toBinary(value: number): stringConverts to a binary string. Example :NumberHandler.toBinary(10)→"1010"toHex(value: number): stringConverts to a hexadecimal string. Example :NumberHandler.toHex(255)→"ff"toRoman(value: number): stringConverts to a Roman numeral. Example :NumberHandler.toRoman(2023)→"MMXXIII"toOrdinal(value: number): stringConverts to ordinal form. Example :NumberHandler.toOrdinal(3)→"3rd"toOrdinalWords(value: number): stringConverts to ordinal words. Example :NumberHandler.toOrdinalWords(3)→"third"toWords(value: number): stringConverts to word representation. Example :NumberHandler.toWords(42)→"forty-two"toBase(value: number, base: number): stringConverts to a specific base. Example :NumberHandler.toBase(15, 16)→"f"abbreviateNumber(value: number, decimals: number): stringAbbreviates with units (k, M, B). Example :NumberHandler.abbreviateNumber(1500000, 1)→"1.5M"toSignificantDigits(value: number, digits: number): numberFormats with significant digits. Example :NumberHandler.toSignificantDigits(123.456, 3)→123
Statistical Operations
sum(numbers: number[]): numberCalculates the sum of an array. Example :NumberHandler.sum([1, 2, 3])→6average(numbers: number[]): numberCalculates the average. Example :NumberHandler.average([2, 4, 6])→4product(numbers: number[]): numberCalculates the product. Example :NumberHandler.product([2, 3, 4])→24max(numbers: number[]): numberFinds the maximum value. Example :NumberHandler.max([1, 5, 3])→5min(numbers: number[]): numberFinds the minimum value. Example :NumberHandler.min([1, 5, 3])→1median(numbers: number[]): numberCalculates the median. Example :NumberHandler.median([1, 3, 5])→3standardDeviation(numbers: number[]): numberCalculates the standard deviation. Example :NumberHandler.standardDeviation([2, 4, 6])→~1.414variance(numbers: number[]): numberCalculates the variance. Example :NumberHandler.variance([2, 4, 6])→~2.667sumOfSquares(numbers: number[]): numberCalculates the sum of squares. Example :NumberHandler.sumOfSquares([2, 3])→13sumOfPowers(numbers: number[], power: number): numberCalculates the sum of powers. Example :NumberHandler.sumOfPowers([2, 3], 2)→13harmonicMean(numbers: number[]): numberCalculates the harmonic mean. Example :NumberHandler.harmonicMean([2, 3, 4])→~2.77mode(numbers: number[]): numberFinds the most frequent value. Example :NumberHandler.mode([1, 2, 2, 3])→2weightedAverage(numbers: number[], weights: number[]): numberCalculates the weighted average. Example :NumberHandler.weightedAverage([1, 2, 3], [0.2, 0.3, 0.5])→2.3arithmeticSum(start: number, end: number, n: number): numberCalculates the sum of an arithmetic sequence. Example :NumberHandler.arithmeticSum(1, 5, 5)→15geometricSum(firstTerm: number, ratio: number, n: number): numberCalculates the sum of a geometric sequence. Example :NumberHandler.geometricSum(2, 2, 3)→14
Random Number Generation
randomInt(min: number, max: number): numberGenerates a random integer. Example :NumberHandler.randomInt(1, 5)→e.g., 3randomFloat(min: number, max: number): numberGenerates a random float. Example :NumberHandler.randomFloat(1, 5)→e.g., 3.456randomNormal(mean: number, stdDev: number): numberGenerates a random number from a normal distribution. Example :NumberHandler.randomNormal(0, 1)→e.g., 0.234randomNormalInt(mean: number, stdDev: number): numberGenerates a random integer from a normal distribution. Example :NumberHandler.randomNormalInt(0, 1)→e.g., 0randomExponential(rate: number): numberGenerates a random number from an exponential distribution. Example :NumberHandler.randomExponential(1)→e.g., 0.693uniqueRandomInts(min: number, max: number, count: number): number[]Generates unique random integers. Example :NumberHandler.uniqueRandomInts(1, 10, 3)→e.g., [7, 2, 9]
Trigonometric Operations
toRadians(degrees: number): numberConverts degrees to radians. Example :NumberHandler.toRadians(180)→~3.142toDegrees(radians: number): numberConverts radians to degrees. Example :NumberHandler.toDegrees(Math.PI)→180cosDegrees(degrees: number): numberCalculates the cosine of an angle in degrees. Example :NumberHandler.cosDegrees(0)→1sinDegrees(degrees: number): numberCalculates the sine of an angle in degrees. Example :NumberHandler.sinDegrees(90)→1tanDegrees(degrees: number): numberCalculates the tangent of an angle in degrees. Example :NumberHandler.tanDegrees(45)→1acosDegrees(value: number): numberCalculates the inverse cosine in degrees. Example :NumberHandler.acosDegrees(1)→0asinDegrees(value: number): numberCalculates the inverse sine in degrees. Example :NumberHandler.asinDegrees(0)→0atanDegrees(value: number): numberCalculates the inverse tangent in degrees. Example :NumberHandler.atanDegrees(1)→45angleBetweenPoints(x1: number, y1: number, x2: number, y2: number): numberCalculates the angle between two points in degrees. Example :NumberHandler.angleBetweenPoints(0, 0, 1, 1)→45
Geometric Operations
hypot(a: number, b: number): numberCalculates the hypotenuse of a right triangle. Example :NumberHandler.hypot(3, 4)→5distance2D(x1: number, y1: number, x2: number, y2: number): numberCalculates the Euclidean distance in 2D. Example :NumberHandler.distance2D(0, 0, 3, 4)→5distance3D(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number): numberCalculates the Euclidean distance in 3D. Example :NumberHandler.distance3D(0, 0, 0, 1, 1, 1)→~1.732manhattanDistance(x1: number, y1: number, x2: number, y2: number): numberCalculates the Manhattan distance in 2D. Example :NumberHandler.manhattanDistance(0, 0, 3, 4)→7midpoint(x1: number, y1: number, x2: number, y2: number): number[]Calculates the midpoint between two points. Example :NumberHandler.midpoint(0, 0, 2, 4)→[1, 2]
Miscellaneous
parseNumber(str: string): numberConverts a numeric string to a number. Example :NumberHandler.parseNumber("123.45")→123.45range(start: number, end: number, step: number): number[]Generates an array of numbers in a range. Example :NumberHandler.range(1, 5)→[1, 2, 3, 4, 5]log(value: number, base: number): numberCalculates the logarithm with a specified base. Example :NumberHandler.log(100, 10)→2sign(value: number): numberReturns the sign of a number. Example :NumberHandler.sign(-5)→-1percentageChange(oldValue: number, newValue: number): numberCalculates the percentage change. Example :NumberHandler.percentageChange(100, 120)→20
ImageHandler
The ImageHandler class provides static methods for image manipulation, conversion, analysis, and applying effects, working with base64 strings or Blobs as input. These methods are designed for common image processing tasks in medium to large-scale projects.
Image Manipulation
resizeImage(input: string | Blob, width: number, height: number, maintainAspectRatio?: boolean): Promise<string>Resizes an image to specified dimensions, optionally maintaining aspect ratio. Example :ImageHandler.resizeImage(base64Image, 200, 200)→ Base64 string of resized imagecropImage(input: string | Blob, x: number, y: number, width: number, height: number): Promise<string>Crops an image to specified coordinates and dimensions. Example :ImageHandler.cropImage(base64Image, 10, 10, 100, 100)→ Base64 string of cropped imagerotateImage(input: string | Blob, angle: number): Promise<string>Rotates an image by a specified angle in degrees. Example :ImageHandler.rotateImage(base64Image, 90)→ Base64 string of rotated imageflipHorizontal(input: string | Blob): Promise<string>Flips an image horizontally. Example :ImageHandler.flipHorizontal(base64Image)→ Base64 string of flipped imageflipVertical(input: string | Blob): Promise<string>Flips an image vertically. Example :ImageHandler.flipVertical(base64Image)→ Base64 string of flipped imageaddBorder(input: string | Blob, borderWidth: number, borderColor: string): Promise<string>Adds a border around an image with specified width and color. Example :ImageHandler.addBorder(base64Image, 5, "black")→ Base64 string of bordered imageaddRoundedCorners(input: string | Blob, radius: number): Promise<string>Adds rounded corners to an image with specified radius. Example :ImageHandler.addRoundedCorners(base64Image, 20)→ Base64 string of rounded imagemergeImages(inputs: (string | Blob)[], direction: "horizontal" | "vertical"): Promise<string>Merges multiple images side by side or stacked. Example :ImageHandler.mergeImages([base64Image1, base64Image2], "horizontal")→ Base64 string of merged imageaddDropShadow(input: string | Blob, options?: { offsetX?: number, offsetY?: number, blur?: number, color?: string }): Promise<string>Adds a drop shadow to an image with customizable options. Example :ImageHandler.addDropShadow(base64Image, { offsetX: 5, offsetY: 5 })→ Base64 string of shadowed imageextractROI(input: string | Blob, threshold: number): Promise<string>Extracts a region of interest based on brightness threshold. Example :ImageHandler.extractROI(base64Image, 128)→ Base64 string of ROI
Image Conversion
convertFormat(input: string | Blob, format: string, quality?: number): Promise<string>Converts an image to a specified format (e.g., JPEG, PNG). Example :ImageHandler.convertFormat(base64Image, "image/png")→ Base64 string of PNG imagetoBlob(input: string | Blob, format: string, quality?: number): Promise<Blob>Converts an image to a Blob. Example :ImageHandler.toBlob(base64Image, "image/jpeg")→ Blob of JPEG imagebase64ToBlob(base64: string, contentType: string): Promise<Blob>Converts a base64 string to a Blob. Example :ImageHandler.base64ToBlob(base64Image, "image/jpeg")→ Blob of imagetoWebP(input: string | Blob, quality?: number): Promise<string>Converts an image to WebP format (if supported). Example :ImageHandler.toWebP(base64Image, 0.8)→ Base64 string of WebP imagecompressImage(input: string | Blob, quality?: number): Promise<string>Compresses an image to reduce file size. Example :ImageHandler.compressImage(base64Image, 0.6)→ Base64 string of compressed image
Image Analysis
getDimensions(input: string | Blob): Promise<{ width: number, height: number }>Gets the dimensions of an image. Example :ImageHandler.getDimensions(base64Image)→{ width: 1920, height: 1080 }isValidImage(input: string | Blob): Promise<boolean>Checks if a base64 string or Blob is a valid image. Example :ImageHandler.isValidImage(base64Image)→truegetDominantColor(input: string | Blob): Promise<{ r: number, g: number, b: number }>Gets the dominant color of an image. Example :ImageHandler.getDominantColor(base64Image)→{ r: 120, g: 100, b: 80 }getColorHistogram(input: string | Blob): Promise<{ r: number[], g: number[], b: number[] }>Generates a color histogram for an image. Example :ImageHandler.getColorHistogram(base64Image)→{ r: [...], g: [...], b: [...] }hasTransparency(input: string | Blob): Promise<boolean>Checks if an image has transparent areas. Example :ImageHandler.hasTransparency(base64Image)→truegetFileSize(input: string | Blob): Promise<number>Gets the file size of an image in bytes. Example :ImageHandler.getFileSize(base64Image)→102400
Image Effects
toGrayscale(input: string | Blob): Promise<string>Converts an image to grayscale. Example :ImageHandler.toGrayscale(base64Image)→ Base64 string of grayscale imageadjustBrightness(input: string | Blob, brightness: number): Promise<string>Adjusts the brightness of an image (-255 to 255). Example :ImageHandler.adjustBrightness(base64Image, 50)→ Base64 string of brighter imageadjustContrast(input: string | Blob, contrast: number): Promise<string>Adjusts the contrast of an image (-100 to 100). Example :ImageHandler.adjustContrast(base64Image, 20)→ Base64 string of contrasted imageapplyBlur(input: string | Blob, radius: number): Promise<string>Applies a blur effect to an image. Example :ImageHandler.applyBlur(base64Image, 5)→ Base64 string of blurred imageapplySepia(input: string | Blob): Promise<string>Applies a sepia effect to an image. Example :ImageHandler.applySepia(base64Image)→ Base64 string of sepia imageadjustSaturation(input: string | Blob, saturation: number): Promise<string>Adjusts the saturation of an image (-100 to 100). Example :ImageHandler.adjustSaturation(base64Image, 50)→ Base64 string of saturated imageinvertColors(input: string | Blob): Promise<string>Inverts the colors of an image. Example :ImageHandler.invertColors(base64Image)→ Base64 string of inverted imageapplyVignette(input: string | Blob, intensity?: number): Promise<string>Applies a vignette effect (darkened edges) to an image. Example :ImageHandler.applyVignette(base64Image, 0.5)→ Base64 string of vignetted imagesharpenImage(input: string | Blob, intensity?: number): Promise<string>Increases the sharpness of an image. Example :ImageHandler.sharpenImage(base64Image, 0.5)→ Base64 string of sharpened imagedetectEdges(input: string | Blob): Promise<string>Detects edges in an image using a Sobel filter. Example :ImageHandler.detectEdges(base64Image)→ Base64 string of edge-detected imagerotateHue(input: string | Blob, degrees: number): Promise<string>Rotates the hue of an image by specified degrees. Example :ImageHandler.rotateHue(base64Image, 90)→ Base64 string of hue-rotated imageposterize(input: string | Blob, levels?: number): Promise<string>Applies a posterize effect by reducing color levels. Example :ImageHandler.posterize(base64Image, 4)→ Base64 string of posterized imageapplyEmboss(input: string | Blob): Promise<string>Applies an emboss effect to an image. Example :ImageHandler.applyEmboss(base64Image)→ Base64 string of embossed imagepixelate(input: string | Blob, pixelSize?: number): Promise<string>Applies a pixelation effect to an image. Example :ImageHandler.pixelate(base64Image, 10)→ Base64 string of pixelated imageapplyColorTint(input: string | Blob, color: { r: number, g: number, b: number }, intensity?: number): Promise<string>Applies a custom color tint to an image. Example :ImageHandler.applyColorTint(base64Image, { r: 255, g: 0, b: 0 }, 0.5)→ Base64 string of tinted imagereduceNoise(input: string | Blob, kernelSize?: number): Promise<string>Reduces noise in an image using an averaging filter. Example :ImageHandler.reduceNoise(base64Image, 3)→ Base64 string of noise-reduced imageapplyWatermark(input: string | Blob, watermarkText: string, options?: { position?: string, font?: string, color?: string, opacity?: number }): Promise<string>Adds a text watermark to an image with customizable options. Example :ImageHandler.applyWatermark(base64Image, "Watermark", { position: "bottom-right" })→ Base64 string of watermarked imagecreateThumbnail(input: string | Blob, maxSize: number): Promise<string>Creates a thumbnail of an image with specified maximum size. Example :ImageHandler.createThumbnail(base64Image, 100)→ Base64 string of thumbnailgeneratePreview(input: string | Blob, scaleFactor?: number): Promise<string>Generates a low-resolution preview of an image. Example :ImageHandler.generatePreview(base64Image, 0.1)→ Base64 string of preview image
ObjectHandler
The ObjectHandler class provides a collection of static methods for object manipulation, validation, transformation, filtering, grouping, analysis, merging, and conversion tasks. These utilities are designed for handling JavaScript objects in real-world scenarios such as API data processing, state management, and data normalization.
Validation
isNonEmptyObject(value: any): booleanChecks if a value is a non-empty plain object. Example :ObjectHandler.isNonEmptyObject({ a: 1 })→trueExample :ObjectHandler.isNonEmptyObject({})→falsehasSameKeys(obj1: Record<string, any>, obj2: Record<string, any>): booleanChecks if two objects have the same keys. Example :ObjectHandler.hasSameKeys({ a: 1, b: 2 }, { a: 3, b: 4 })→trueisSubset(subset: Record<string, any>, superset: Record<string, any>): booleanChecks if one object is a subset of another. Example :ObjectHandler.isSubset({ a: 1 }, { a: 1, b: 2 })→truehasAllKeys(obj: Record<string, any>, keys: string[]): booleanChecks if an object contains all specified keys. Example :ObjectHandler.hasAllKeys({ a: 1, b: 2 }, ['a', 'b'])→truematchesTemplate(obj: Record<string, any>, template: Record<string, any>): booleanChecks if an object matches a partial template. Example :ObjectHandler.matchesTemplate({ a: 1, b: 2 }, { a: 1 })→truehasOnlyTypes(obj: Record<string, any>, types: string[]): booleanChecks if an object contains only specified types for its values. Example :ObjectHandler.hasOnlyTypes({ a: 'x', b: 'y' }, ['string'])→truehasNestedObjects(obj: Record<string, any>): booleanChecks if an object contains nested objects. Example :ObjectHandler.hasNestedObjects({ a: { b: 1 } })→truevalidateSchema(obj: Record<string, any>, schema: Record<string, string>): Record<string, any>Validates an object against a schema, keeping only valid key-value pairs. Example :ObjectHandler.validateSchema({ name: 'John', age: 30 }, { name: 'string', age: 'number' })→{ name: 'John', age: 30 }validateValues(obj: Record<string, any>, validator: (value: any, key: string) => boolean): Record<string, any>Validates values using a custom validator function, keeping only valid pairs. Example :ObjectHandler.validateValues({ a: 1, b: 2 }, v => v > 1)→{ b: 2 }validateNonNullValues(obj: Record<string, any>): Record<string, any>Validates values, keeping only non-null and non-undefined values. Example :ObjectHandler.validateNonNullValues({ a: null, b: 1 })→{ b: 1 }
Transformation
toCamelCaseKeys(obj: Record<string, any>): Record<string, any>Converts object keys to camelCase. Example :ObjectHandler.toCamelCaseKeys({ first_name: 1 })→{ firstName: 1 }toSnakeCaseKeys(obj: Record<string, any>): Record<string, any>Converts object keys to snake_case. Example :ObjectHandler.toSnakeCaseKeys({ firstName: 1 })→{ first_name: 1 }toTitleCaseKeys(obj: Record<string, any>): Record<string, any>Converts object keys to title case. Example :ObjectHandler.toTitleCaseKeys({ first_name: 1 })→{ First Name: 1 }sortKeys(obj: Record<string, any>): Record<string, any>Sorts object keys alphabetically. Example :ObjectHandler.sortKeys({ b: 2, a: 1 })→{ a: 1, b: 2 }invertObject(obj: Record<string, any>): Record<string, any>Inverts key-value pairs (values become keys, keys become values). Example :ObjectHandler.invertObject({ a: 'x' })→{ x: 'a' }renameKeys(obj: Record<string, any>, keyMap: Record<string, string>): Record<string, any>Renames keys based on a mapping. Example :ObjectHandler.renameKeys({ old: 1 }, { old: 'new' })→{ new: 1 }prefixKeys(obj: Record<string, any>, prefix: string): Record<string, any>Adds a prefix to each key. Example :ObjectHandler.prefixKeys({ a: 1 }, 'pre_')→{ pre_a: 1 }toUpperCaseValues(obj: Record<string, any>): Record<string, any>Converts string values to uppercase. Example :ObjectHandler.toUpperCaseValues({ a: 'hello' })→{ a: 'HELLO' }convertValuesType(obj: Record<string, any>, type: 'string' | 'number' | 'boolean'): Record<string, any>Converts values to a specific type. Example :ObjectHandler.convertValuesType({ a: '1' }, 'number')→{ a: 1 }replaceValues(obj: Record<string, any>, valueMap: Record<string, any>): Record<string, any>Replaces values based on a mapping. Example :ObjectHandler.replaceValues({ a: 'x' }, { x: 'y' })→{ a: 'y' }normalizeValues(obj: Record<string, any>): Record<string, any>Normalizes string values by trimming and removing excess whitespace. Example :ObjectHandler.normalizeValues({ a: ' hello ' })→{ a: 'hello' }transformKeys(obj: Record<string, any>, callback: (key: string) => string): Record<string, any>Transforms keys using a callback function. Example :ObjectHandler.transformKeys({ a: 1 }, k => k.toUpperCase())→{ A: 1 }replaceByCondition(obj: Record<string, any>, condition: (value: any, key: string) => boolean, defaultValue: any): Record<string, any>Replaces values matching a condition with a default value. Example :ObjectHandler.replaceByCondition({ a: 0 }, v => v === 0, 1)→{ a: 1 }replaceFalsy(obj: Record<string, any>, fallback: any): Record<string, any>Replaces falsy values with a fallback value. Example :ObjectHandler.replaceFalsy({ a: 0 }, 'default')→{ a: 'default' }mapByType(obj: Record<string, any>, typeMap: Record<string, (value: any) => any>): Record<string, any>Maps values based on their type using transformation functions. Example :ObjectHandler.mapByType({ a: 'x' }, { string: v => v.toUpperCase() })→{ a: 'X' }truncateStringValues(obj: Record<string, any>, maxLength: number): Record<string, any>Truncates string values to a maximum length. Example :ObjectHandler.truncateStringValues({ a: 'hello' }, 3)→{ a: 'hel' }computeValues(obj: Record<string, any>, compute: (value: any, key: string, obj: Record<string, any>) => any): Record<string, any>Replaces values with computed values based on the object. Example :ObjectHandler.computeValues({ a: 1 }, v => v * 2)→{ a: 2 }standardizeValues(obj: Record<string, any>): Record<string, any>Standardizes values (e.g., converts dates to ISO format). Example :ObjectHandler.standardizeValues({ a: new Date('2023-01-01') })→{ a: '2023-01-01T00:00:00.000Z' }transformStringCase(obj: Record<string, any>, caseType: 'upper' | 'lower'): Record<string, any>Transforms string values to upper or lower case. Example :ObjectHandler.transformStringCase({ a: 'hello' }, 'upper')→{ a: 'HELLO' }normalizeNumericValues(obj: Record<string, any>, options: { decimalPlaces?: number }): Record<string, any>Normalizes numeric values to a fixed number of decimal places. Example :ObjectHandler.normalizeNumericValues({ a: 1.234 }, { decimalPlaces: 2 })→{ a: 1.23 }toPrimitiveValues(obj: Record<string, any>): Record<string, any>Converts values to their primitive equivalents (e.g., objects to strings). Example :ObjectHandler.toPrimitiveValues({ a: { b: 1 } })→{ a: '{"b":1}' }
Filtering
omitKeys(obj: Record<string, any>, keys: string[]): Record<string, any>Omits specified keys from an object. Example :ObjectHandler.omitKeys({ a: 1, b: 2 }, ['b'])→{ a: 1 }removeNullValues(obj: Record<string, any>): Record<string, any>Removes null or undefined values from an object. Example :ObjectHandler.removeNullValues({ a: null, b: 1 })→{ b: 1 }keepTruthyValues(obj: Record<string, any>): Record<string, any>Keeps only truthy values in an object. Example :ObjectHandler.keepTruthyValues({ a: 0, b: 1 })→{ b: 1 }uniqueValues(obj: Record<string, any>): Record<string, any>Removes duplicate values, keeping the first occurrence. Example :ObjectHandler.uniqueValues({ a: 1, b: 1 })→{ a: 1 }takeN(obj: Record<string, any>, n: number): Record<string, any>Keeps only the first N key-value pairs. Example :ObjectHandler.takeN({ a: 1, b: 2 }, 1)→{ a: 1 }filterByKeyPattern(obj: Record<string, any>, pattern: RegExp): Record<string, any>Filters keys matching a regex pattern. Example :ObjectHandler.filterByKeyPattern({ abc: 1, xyz: 2 }, /^a/)→{ abc: 1 }filterByPrefix(obj: Record<string, any>, prefix: string): Record<string, any>Filters keys starting with a prefix. Example :ObjectHandler.filterByPrefix({ pre_a: 1, b: 2 }, 'pre_')→{ pre_a: 1 }filterObjectValues(obj: Record<string, any>): Record<string, any>Filters keys whose values are objects. Example :ObjectHandler.filterObjectValues({ a: { b: 1 }, c: 2 })→{ a: { b: 1 } }omitByCondition(obj: Record<string, any>, condition: (value: any, key: string) => boolean): Record<string, any>Omits keys matching a condition. Example :ObjectHandler.omitByCondition({ a: 1 }, v => v === 1)→{}filterNonEmptyArrays(obj: Record<string, any>): Record<string, any>Filters keys with non-empty array values. Example :ObjectHandler.filterNonEmptyArrays({ a: [], b: [1] })→{ b: [1] }filterByDepth(obj: Record<string, any>, maxDepth: number): Record<string, any>Filters keys up to a specified nested depth. Example :ObjectHandler.filterByDepth({ a: { b: 1 } }, 1)→{ a: { b: 1 } }filterByValueComparator(obj: Record<string, any>, comparator: (value: any) => boolean): Record<string, any>Filters keys whose values pass a comparator. Example :ObjectHandler.filterByValueComparator({ a: 1 }, v => v > 0)→{ a: 1 }filterByReferenceValues(obj: Record<string, any>, reference: Record<string, any>): Record<string, any>Filters keys whose values exist in a reference object. Example :ObjectHandler.filterByReferenceValues({ a: 'x' }, { b: 'x' })→{ a: 'x' }filterByAllowedKeys(obj: Record<string, any>, allowedKeys: string[]): Record<string, any>Filters keys present in a reference array. Example :ObjectHandler.filterByAllowedKeys({ a: 1, b: 2 }, ['a'])→{ a: 1 }
Grouping
groupBy(arr: Record<string, any>[], key: string): Record<string, any[]>Groups an array of objects by a key. Example :ObjectHandler.groupBy([{ id: 1 }, { id: 1 }], 'id')→{ '1': [{ id: 1 }, { id: 1 }] }groupByType(obj: Record<string, any>): Record<string, Record<string, any>>Groups keys by value type. Example :ObjectHandler.groupByType({ a: 'x', b: 1 })→{ string: { a: 'x' }, number: { b: 1 } }aggregateByKey(arr: Record<string, any>[], key: string, valueKey: string): Record<string, any[]>Aggregates values by a key from an array of objects. Example :ObjectHandler.aggregateByKey([{ id: 1, val: 'x' }], 'id', 'val')→{ '1': ['x'] }groupByValueRange(obj: Record<string, any>, ranges: { min: number; max: number; label: string }[]): Record<string, Record<string, any>>Groups keys by numeric value ranges. Example :ObjectHandler.groupByValueRange({ a: 5 }, [{ min: 0, max: 10, label: 'low' }])→{ low: { a: 5 } }
Analysis
countValues(obj: Record<string, any>): Record<string, number>Counts occurrences of values in an object. Example :ObjectHandler.countValues({ a: 'x', b: 'x' })→{ x: 2 }containsValue(obj: Record<string, any>, value: any): booleanChecks if an object contains a specific value. Example :ObjectHandler.containsValue({ a: 1 }, 1)→truegetTypeSummary(obj: Record<string, any>): Record<string, number>Summarizes the count of each data type in values. Example :ObjectHandler.getTypeSummary({ a: 'x', b: 1 })→{ string: 1, number: 1 }mapToStringLengths(obj: Record<string, any>): Record<string, any>Maps string values to their lengths, keeps others unchanged. Example :ObjectHandler.mapToStringLengths({ a: 'hi' })→{ a: 2 }diffObjects(obj1: Record<string, any>, obj2: Record<string, any>): Record<string, { from: any; to: any }>Finds differences between two objects. Example :ObjectHandler.diffObjects({ a: 1 }, { a: 2 })→{ a: { from: 1, to: 2 } }keyToIndexMap(obj: Record<string, any>): Record<string, number>Maps keys to their indices in key order. Example :ObjectHandler.keyToIndexMap({ a: 1, b: 2 })→{ a: 0, b: 1 }mapToHashCode(obj: Record<string, any>): Record<string, number>Maps values to simple hash codes. Example :ObjectHandler.mapToHashCode({ a: 'x' })→{ a: <hash> }mapToParentKeys(obj: Record<string, any>, parentKey?: string): Record<string, string>Maps keys to their parent keys in a nested structure. Example :ObjectHandler.mapToParentKeys({ a: { b: 1 } })→{ a: 'a', b: 'a.b' }mapToValueFrequency(obj: Record<string, any>): Record<string, number>Maps keys to their value's frequency. Example :ObjectHandler.mapToValueFrequency({ a: 'x', b: 'x' })→{ a: 2, b: 2 }mapToValueMetadata(obj: Record<string, any>): Record<string, { type: string; length?: number }>Maps keys to value metadata (type, length). Example :ObjectHandler.mapToValueMetadata({ a: 'hi' })→{ a: { type: 'string', length: 2 } }mapToKeyOrder(obj: Record<string, any>): Record<string, number>Maps keys to their order index. Example :ObjectHandler.mapToKeyOrder({ a: 1, b: 2 })→{ a: 0, b: 1 }mapToSerializedSize(obj: Record<string, any>): Record<string, number>Maps keys to their value's serialized size in bytes. Example :ObjectHandler.mapToSerializedSize({ a: 'hi' })→{ a: 4 }mapToRegexValidation(obj: Record<string, any>, pattern: RegExp): Record<string, boolean>Maps keys to their value's regex validation status. Example :ObjectHandler.mapToRegexValidation({ a: 'abc' }, /^abc$/)→{ a: true }
Merging
withDefaults(obj: Record<string, any>, defaults: Record<string, any>): Record<string, any>Adds default values for missing keys. Example :ObjectHandler.withDefaults({ a: 1 }, { b: 2 })→{ a: 1, b: 2 }mergeIntoArrays(objects: Record<string, any>[]): Record<string, any[]>Merges an array of objects, combining values into arrays. Example :ObjectHandler.mergeIntoArrays([{ a: 1 }, { a: 2 }])→{ a: [1, 2] }selectiveMerge(target: Record<string, any>, source: Record<string, any>, keys: string[]): Record<string, any>Merges objects, including only specified keys from the source. Example :ObjectHandler.selectiveMerge({ a: 1 }, { b: 2 }, ['b'])→{ a: 1, b: 2 }mergeNestedValues(obj: Record<string, any>, prefix?: string): Record<string, any>Merges nested object values into the top level. Example :ObjectHandler.mergeNestedValues({ a: { b: 1 } }, 'pre')→{ pre_a_b: 1 }
Conversion
toMap(obj: Record<string, any>): Map<string, any>Converts an object to a Map. Example :ObjectHandler.toMap({ a: 1 })→Map { 'a' => 1 }fromMap(map: Map<string, any>): Record<string, any>Converts a Map to an object. Example :ObjectHandler.fromMap(new Map([['a', 1]]))→{ a: 1 }getValues(obj: Record<string, any>): any[]Gets object values as an array. Example :ObjectHandler.getValues({ a: 1, b: 2 })→[1, 2]flattenToDepth(obj: Record<string, any>, depth?: number): Record<string, any>Flattens nested objects to a specified depth. Example :ObjectHandler.flattenToDepth({ a: { b: 1 } }, 1)→{ 'a.b': 1 }shallowCloneValues(obj: Record<string, any>): Record<string, any>Creates a shallow clone of values to prevent reference sharing. Example :ObjectHandler.shallowCloneValues({ a: [1] })→{ a: [1] }flattenArrayValues(obj: Record<string, any>): Record<string, any>Flattens nested array values to a single level. Example :ObjectHandler.flattenArrayValues({ a: [[1, 2]] })→{ a: [1, 2] }parseJsonValues(obj: Record<string, any>): Record<string, any>Parses string values as JSON where possible. Example :ObjectHandler.parseJsonValues({ a: '{"b":1}' })→{ a: { b: 1 } }
Miscellaneous
reduceObject<T, U>(obj: Record<string, T>, callback: (acc: U, value: T, key: string) => U, initialValue: U): UReduces an object to a single value using a callback. Example :ObjectHandler.reduceObject({ a: 1, b: 2 }, (acc, v) => acc + v, 0)→3sortByValues(obj: Record<string, any>, descending?: boolean): Record<string, any>Sorts keys by their values. Example :ObjectHandler.sortByValues({ a: 2, b: 1 })→{ b: 1, a: 2 }partitionBy(obj: Record<string, any>, predicate: (value: any, key: string) => boolean): [Record<string, any>, Record<string, any>]Partitions an object into two based on a predicate. Example :ObjectHandler.partitionBy({ a: 1, b: 2 }, v => v > 1)→[{ b: 2 }, { a: 1 }]getEnumerableProperties(obj: Record<string, any>): Record<string, any>Gets only enumerable properties of an object. Example :ObjectHandler.getEnumerableProperties({ a: 1 })→{ a: 1 }swapKeysValues(obj: Record<string, any>): Record<string, any>Swaps keys and values, keeping the last key for non-unique values. Example :ObjectHandler.swapKeysValues({ a: 'x' })→{ x: 'a' }deduplicateNestedValues(obj: Record<string, any>): Record<string, any>Deduplicates values across nested objects. Example :ObjectHandler.deduplicateNestedValues({ a: 'x', b: { c: 'x' } })→{ a: 'x', b: {} }
DateTimeHandler
The DateTimeHandler class provides static methods for date and time manipulation, validation, formatting, conversion, calculation, comparison, and analysis. These utilities are designed for real-world scenarios such as API data processing, user interface display, scheduling, and time analysis.
Validation
isValidDate(value: any): booleanChecks if a value is a valid Date object. Example :DateTimeHandler.isValidDate(new Date())→trueisInRange(date: Date, start: Date, end: Date): booleanChecks if a Date is within a specified range. Example :DateTimeHandler.isInRange(new Date('2025-07-25'), new Date('2025-07-01'), new Date('2025-07-31'))→trueisSameDay(date1: Date, date2: Date): booleanChecks if two Dates are on the same day. Example :DateTimeHandler.isSameDay(new Date('2025-07-25'), new Date('2025-07-25'))→trueisLeapYear(year: number): booleanChecks if a year is a leap year. Example :DateTimeHandler.isLeapYear(2024)→trueisWeekend(date: Date): booleanChecks if a Date is a weekend day (Saturday or Sunday). Example :DateTimeHandler.isWeekend(new Date('2025-07-26'))→trueisInMonth(date: Date, month: number): booleanChecks if a Date falls in a specific month. Example :DateTimeHandler.isInMonth(new Date('2025-07-25'), 6)→true- **`isInYear(date: Date, yea
