npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@hphudev/utils

v2.0.4

Published

Common utility functions in JS/TS

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/utils

Ensure 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: 5

StringHandler

The StringHandler class provides a collection of static methods for string manipulation, validation, analysis, extraction, and generation.

String Transformation

  • capitalize(str: string): string Capitalizes the first letter of a string. Example : StringHandler.capitalize("hello")"Hello"
  • slugify(str: string): string Converts a string into a URL-friendly slug. Example : StringHandler.slugify("Xin Chào bạn ơi!")"xin-chao-ban-oi"
  • toCamelCase(str: string): string Converts a string to camelCase. Example : StringHandler.toCamelCase("hello-world")"helloWorld"
  • toSnakeCase(str: string): string Converts a string to snake_case. Example : StringHandler.toSnakeCase("helloWorld")"hello_world"
  • toKebabCase(str: string): string Converts a string to kebab-case. Example : StringHandler.toKebabCase("helloWorld")"hello-world"
  • toPascalCase(str: string): string Converts a string to PascalCase. Example : StringHandler.toPascalCase("hello-world")"HelloWorld"
  • toTitleCase(str: string): string Converts a string to title case. Example : StringHandler.toTitleCase("hello world")"Hello World"
  • toSentenceCase(str: string): string Converts a string to sentence case. Example : StringHandler.toSentenceCase("hello WORLD")"Hello world"
  • toHyphenated(str: string): string Converts a string to hyphenated lowercase. Example : StringHandler.toHyphenated("Hello World")"hello-world"
  • toCustomSlug(str: string, separator: string = '-'): string Creates a slug with a custom separator. Example : StringHandler.toCustomSlug("Hello World", "_")"hello_world"
  • toLimitedKebabCase(str: string, maxLength: number = 50): string Converts to kebab-case with a length limit. Example : StringHandler.toLimitedKebabCase("Hello World Example", 10)"hello-world"
  • toLocaleUpperCase(str: string, locale: string = 'en-US'): string Converts to uppercase with locale support. Example : StringHandler.toLocaleUpperCase("hello")"HELLO"
  • toLocaleLowerCase(str: string, locale: string = 'en-US'): string Converts to lowercase with locale support. Example : StringHandler.toLocaleLowerCase("HELLO")"hello"
  • toBase64(str: string): string Encodes to Base64. Example : StringHandler.toBase64("hello")"aGVsbG8="
  • fromBase64(str: string): string Decodes from Base64. Example : StringHandler.fromBase64("aGVsbG8=")"hello"
  • normalize(str: string): string Removes diacritics from a string. Example : StringHandler.normalize("Héllô Wørld")"Hello World"
  • truncate(str: string, length: number, ending: string = '...'): string Truncates a string if it exceeds the specified length. Example : StringHandler.truncate("Hello world", 5)"He..."
  • truncateWords(str: string, maxWords: number, ending: string = '...'): string Truncates to a specified number of words. Example : StringHandler.truncateWords("Hello world this is a test", 3)"Hello world this..."
  • reverse(str: string): string Reverses the characters of a string. Example : StringHandler.reverse("hello")"olleh"
  • capitalizeWords(str: string): string Capitalizes the first letter of each word. Example : StringHandler.capitalizeWords("hello world")"Hello World"
  • capitalizeSentences(str: string): string Capitalizes the first letter of each sentence. Example : StringHandler.capitalizeSentences("hello. world!")"Hello. World!"
  • removeWhitespace(str: string): string Removes all whitespace characters. Example : StringHandler.removeWhitespace(" hello world ")"helloworld"
  • removeSpecialCharacters(str: string): string Removes special characters, keeping alphanumerics and spaces. Example : StringHandler.removeSpecialCharacters("Hello! @World#")"Hello World"
  • keepAlphanumeric(str: string): string Removes non-alphanumeric characters. Example : StringHandler.keepAlphanumeric("Hello!@123")"Hello123"
  • trimChars(str: string, chars: string = ' '): string Trims specific characters from both ends. Example : StringHandler.trimChars("##hello##", "#")"hello"
  • repeat(str: string, times: number): string Repeats a string a specified number of times. Example : StringHandler.repeat("abc", 3)"abcabcabc"
  • removeDuplicates(str: string): string Removes duplicate characters. Example : StringHandler.removeDuplicates("hello")"helo"
  • deduplicateChar(str: string, char: string): string Replaces multiple consecutive occurrences of a character with a single one. Example : StringHandler.deduplicateChar("hello----world", "-")"hello-world"
  • toSafeFilePath(str: string): string Sanitizes a string for safe use in file paths. Example : StringHandler.toSafeFilePath("My:Doc/ument.txt")"My_Document.txt"
  • urlEncode(str: string): string Converts to URL-encoded format. Example : StringHandler.urlEncode("hello world!")"hello%20world%21"
  • urlDecode(str: string): string Decodes a URL-encoded string. Example : StringHandler.urlDecode("hello%20world%21")"hello world!"
  • escapeHtml(str: string): string Escapes HTML special characters. Example : StringHandler.escapeHtml("<p>Hello & World</p>")"&lt;p&gt;Hello &amp; World&lt;/p&gt;"
  • unescapeHtml(str: string): string Unescapes HTML entities. Example : StringHandler.unescapeHtml("&lt;p&gt;Hello &amp; World&lt;/p&gt;")"<p>Hello & World</p>"
  • stripHtml(str: string): string Removes HTML tags. Example : StringHandler.stripHtml("<p>Hello</p>")"Hello"
  • toQueryString(str: string): string Converts a string to a URL query string. Example : StringHandler.toQueryString("name=John&age=30")"name=John&age=30"
  • formatString(str: string, ...args: string[]): string Formats a string by replacing placeholders. Example : StringHandler.formatString("Hello, {0}!", "World")"Hello, World!"
  • formatPhoneNumber(str: string, format: string): string Formats a phone number according to a template. Example : StringHandler.formatPhoneNumber("1234567890", "(###) ###-####")"(123) 456-7890"
  • toCurrency(str: string, currency: string = 'USD', locale: string = 'en-US'): string Converts a numeric string to a formatted currency string. Example : StringHandler.toCurrency("1234.56")"$1,234.56"
  • toReadableDate(str: string): string Converts an ISO date string to a readable format. Example : StringHandler.toReadableDate("2025-07-25")"July 25, 2025"
  • toFileSize(str: string): string Converts a numeric string (bytes) to a human-readable file size. Example : StringHandler.toFileSize("1048576")"1 MB"
  • padLeft(str: string, length: number, padChar: string = ' '): string Pads a string with a character on the left. Example : StringHandler.padLeft("123", 5, "0")"00123"
  • padRight(str: string, length: number, padChar: string = ' '): string Pads a string with a character on the right. Example : StringHandler.padRight("123", 5, "0")"12300"
  • mask(str: string, start: number, length: number, maskChar: string = '*'): string Masks a portion of a string. Example : StringHandler.mask("1234567890", 4, 4)"1234****90"
  • removeLeadingZeros(str: string): string Removes leading zeros from a numeric string. Example : StringHandler.removeLeadingZeros("00123")"123"

String Validation

  • isEmail(str: string): boolean Checks if a string is a valid email address. Example : StringHandler.isEmail("[email protected]")true
  • isUrl(str: string): boolean Validates if a string is a valid URL. Example : StringHandler.isUrl("https://example.com")true
  • isUUID(str: string): boolean Validates if a string is a valid UUID v4. Example : StringHandler.isUUID("550e8400-e29b-41d4-a716-446655440000")true
  • isAnyUUID(str: string): boolean Checks if a string is a valid UUID (any version). Example : StringHandler.isAnyUUID("123e4567-e89b-12d3-a456-426614174000")true
  • isVietnamesePhone(str: string): boolean Validates a Vietnamese phone number. Example : StringHandler.isVietnamesePhone("0901234567")true
  • isValidDate(str: string): boolean Checks if a string is a valid ISO date (YYYY-MM-DD). Example : StringHandler.isValidDate("2025-07-25")true
  • isBlank(str: string): boolean Checks if a string is empty or contains only whitespace. Example : StringHandler.isBlank(" ")true
  • isNumeric(str: string): boolean Checks if a string contains only digits. Example : StringHandler.isNumeric("123")true
  • isAlphabetic(str: string): boolean Checks if a string contains only alphabetic characters. Example : StringHandler.isAlphabetic("Hello")true
  • isAlphanumeric(str: string): boolean Checks if a string contains only alphanumeric characters. Example : StringHandler.isAlphanumeric("Hello123")true
  • isHex(str: string): boolean Checks if a string is a valid hexadecimal string. Example : StringHandler.isHex("1a2b3c")true
  • isHexColor(str: string): boolean Checks if a string is a valid hexadecimal color code. Example : StringHandler.isHexColor("#FF0000")true
  • isCssColor(str: string): boolean Checks if a string is a valid CSS color name. Example : StringHandler.isCssColor("red")true
  • isIPv4(str: string): boolean Checks if a string is a valid IPv4 address. Example : StringHandler.isIPv4("192.168.1.1")true
  • isMacAddress(str: string): boolean Checks if a string is a valid MAC address. Example : StringHandler.isMacAddress("00:1A:2B:3C:4D:5E")true
  • isIsbn(str: string): boolean Checks if a string is a valid ISBN-10 or ISBN-13. Example : StringHandler.isIsbn("978-3-16-148410-0")true
  • isValidPassword(str: string, minLength: number = 8, requireSpecial: boolean = true): boolean Checks if a string meets password requirements. Example : StringHandler.isValidPassword("Password123!")true
  • isInternationalPhone(str: string): boolean Validates an international phone number. Example : StringHandler.isInternationalPhone("+12025550123")true
  • isJson(str: string): boolean Checks if a string is valid JSON. Example : StringHandler.isJson('{"key": "value"}')true
  • isMongoId(str: string): boolean Checks if a string is a valid MongoDB ObjectId. Example : StringHandler.isMongoId("507f1f77bcf86cd799439011")true
  • isJwt(str: string): boolean Checks if a string is a valid JWT token format. Example : StringHandler.isJwt("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dummysig")true
  • isBase64Image(str: string): boolean Checks if a string is a valid base64-encoded image. Example : StringHandler.isBase64Image("data:image/png;base64,iVBORw0KGgo=")true
  • isTime(str: string): boolean Checks if a string is a valid time in HH:MM or HH:MM:SS format. Example : StringHandler.isTime("14:30")true
  • isPostalCode(str: string, countryCode: string = 'US'): boolean Validates a postal code for a given country. Example : StringHandler.isPostalCode("90210", "US")true
  • isValidFileName(str: string): boolean Checks if a string is a valid file name. Example : StringHandler.isValidFileName("document.txt")true
  • isPrintableAscii(str: string): boolean Checks if a string contains only printable ASCII characters. Example : StringHandler.isPrintableAscii("Hello123!")true
  • isDomain(str: string): boolean Validates if a string is a valid domain name. Example : StringHandler.isDomain("example.com")true
  • isSlug(str: string): boolean Validates if a string is a valid slug. Example : StringHandler.isSlug("hello-world")true

String Analysis

  • countOccurrences(str: string, searchStr: string): number Counts occurrences of a substring. Example : StringHandler.countOccurrences("hello hello", "hello")2
  • isPalindrome(str: string): boolean Checks if a string is a palindrome. Example : StringHandler.isPalindrome("racecar")true
  • isAnagram(str1: string, str2: string): boolean Checks if two strings are anagrams. Example : StringHandler.isAnagram("listen", "silent")true
  • contains(str: string, substring: string): boolean Checks if a string contains a substring. Example : StringHandler.contains("Hello world", "world")true
  • startsWith(str: string, prefix: string): boolean Checks if a string starts with a prefix. Example : StringHandler.startsWith("Hello world", "Hello")true
  • endsWith(str: string, suffix: string): boolean Checks if a string ends with a suffix. Example : StringHandler.endsWith("Hello world", "world")true
  • hasEmoji(str: string): boolean Checks if a string contains emojis. Example : StringHandler.hasEmoji("Hello 😊")true
  • isBalancedParentheses(str: string): boolean Checks if a string has balanced parentheses. Example : StringHandler.isBalancedParentheses("(hello (world))")true
  • matches(str: string, regex: RegExp): boolean Checks if a string matches a regular expression. Example : StringHandler.matches("hello123", /^[a-z0-9]+$/i)true
  • matchesAny(str: string, patterns: RegExp[]): boolean Checks if a string matches any of the provided regex patterns. Example : StringHandler.matchesAny("hello123", [/^[a-z0-9]+$/, /^\d+$/])true
  • hashCode(str: string): number Generates a numeric hash code for a string. Example : StringHandler.hashCode("hello")99162322

String Extraction

  • extractNumbers(str: string): string Extracts 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): string Extracts the domain from a URL. Example : StringHandler.extractDomain("https://example.com/path")"example.com"
  • getFileExtension(str: string): string Extracts the file extension from a file name. Example : StringHandler.getFileExtension("document.pdf")"pdf"

String Generation

  • randomString(length: number = 8): string Generates a random alphanumeric string. Example : StringHandler.randomString(6)"A1b2Cd"
  • randomLowercase(length: number = 8): string Generates a random lowercase string. Example : StringHandler.randomLowercase(6)"abcdef"
  • randomUppercase(length: number = 8): string Generates a random uppercase string. Example : StringHandler.randomUppercase(6)"ABCDEF"
  • generatePattern(pattern: string): string Generates a random string based on a pattern. Example : StringHandler.generatePattern("xxx-###")"abc-123"

Miscellaneous

  • toNumber(str: string, defaultValue: number = 0): number Converts a string to a number. Example : StringHandler.toNumber("123.45")123.45
  • toBoolean(str: string): boolean Converts a string to a boolean. Example : StringHandler.toBoolean("true")true
  • chunk(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 = ''): boolean Checks if a string contains only whitespace or allowed characters. Example : StringHandler.isWhitespaceOr(" \t\n", "\t\n")true
  • replaceAll(str: string, search: string, replacement: string): string Replaces 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): boolean Checks if a value is a valid number. Example : NumberHandler.isValidNumber(123)true
  • isInteger(value: any): boolean Checks if a value is an integer. Example : NumberHandler.isInteger(5)true
  • isEven(value: number): boolean Checks if a number is even. Example : NumberHandler.isEven(4)true
  • isOdd(value: number): boolean Checks if a number is odd. Example : NumberHandler.isOdd(5)true
  • isPositive(value: number): boolean Checks if a number is positive. Example : NumberHandler.isPositive(5)true
  • isNegative(value: number): boolean Checks if a number is negative. Example : NumberHandler.isNegative(-5)true
  • isZero(value: number): boolean Checks if a number is zero. Example : NumberHandler.isZero(0)true
  • isInRange(value: number, min: number, max: number): boolean Checks if a number is within a range. Example : NumberHandler.isInRange(5, 1, 10)true
  • isPrime(value: number): boolean Checks if a number is prime. Example : NumberHandler.isPrime(17)true
  • isPerfectSquare(value: number): boolean Checks if a number is a perfect square. Example : NumberHandler.isPerfectSquare(16)true
  • isPowerOfTwo(value: number): boolean Checks if a number is a power of two. Example : NumberHandler.isPowerOfTwo(8)true
  • isTriangular(value: number): boolean Checks if a number is triangular. Example : NumberHandler.isTriangular(6)true
  • isPalindrome(value: number): boolean Checks if a number is a palindrome. Example : NumberHandler.isPalindrome(12321)true
  • isPerfectNumber(value: number): boolean Checks if a number is perfect. Example : NumberHandler.isPerfectNumber(6)true
  • isFibonacci(value: number): boolean Checks if a number is a Fibonacci number. Example : NumberHandler.isFibonacci(8)true
  • isArmstrong(value: number): boolean Checks if a number is an Armstrong number. Example : NumberHandler.isArmstrong(153)true
  • isMultiple(value: number, divisor: number): boolean Checks if a number is a multiple of another. Example : NumberHandler.isMultiple(15, 5)true
  • isPowerOf(value: number, base: number): boolean Checks if a number is a power of a given base. Example : NumberHandler.isPowerOf(16, 2)true
  • isWithinTolerance(value: number, target: number, tolerance: number): boolean Checks if a number is within a tolerance of a target. Example : NumberHandler.isWithinTolerance(10.1, 10, 0.5)true
  • approxEqual(a: number, b: number, epsilon: number): boolean Checks if two numbers are approximately equal. Example : NumberHandler.approxEqual(1.0000001, 1, 0.0001)true
  • isHappy(value: number): boolean Checks if a number is happy. Example : NumberHandler.isHappy(19)true

Number Manipulation

  • abs(value: number): number Returns the absolute value. Example : NumberHandler.abs(-10)10
  • pow(base: number, exponent: number): number Calculates the power of a number. Example : NumberHandler.pow(2, 3)8
  • sqrt(value: number): number Calculates the square root. Example : NumberHandler.sqrt(16)4
  • nthRoot(value: number, n: number): number Calculates the nth root. Example : NumberHandler.nthRoot(8, 3)2
  • clamp(value: number, min: number, max: number): number Clamps a number between a minimum and maximum. Example : NumberHandler.clamp(10, 0, 5)5
  • clampToInt(value: number, min: number, max: number): number Clamps a number to an integer within a range. Example : NumberHandler.clampToInt(5.7, 0, 5)5
  • roundTo(value: number, decimals: number): number Rounds to a specified number of decimal places. Example : NumberHandler.roundTo(3.14159, 2)3.14
  • truncate(value: number, decimals: number): number Truncates to a specified number of decimal places. Example : NumberHandler.truncate(3.14159, 2)3.14
  • roundToNearest(value: number, multiple: number): number Rounds to the nearest multiple. Example : NumberHandler.roundToNearest(17, 5)15
  • roundToEven(value: number): number Rounds to the nearest even integer. Example : NumberHandler.roundToEven(3.7)4
  • ceil(value: number): number Rounds up to the nearest integer. Example : NumberHandler.ceil(3.14)4
  • floor(value: number): number Rounds down to the nearest integer. Example : NumberHandler.floor(3.86)3
  • mod(value: number, divisor: number): number Calculates modulo with a non-negative result. Example : NumberHandler.mod(-7, 3)2
  • factorial(value: number): number Calculates the factorial. Example : NumberHandler.factorial(5)120
  • fibonacci(n: number): number Calculates the nth Fibonacci number. Example : NumberHandler.fibonacci(6)8
  • lerp(start: number, end: number, t: number): number Linearly interpolates between two numbers. Example : NumberHandler.lerp(0, 100, 0.5)50
  • normalize(value: number, oldMin: number, oldMax: number, newMin: number, newMax: number): number Normalizes a number to a new range. Example : NumberHandler.normalize(50, 0, 100, 0, 1)0.5
  • gcd(a: number, b: number): number Calculates the greatest common divisor. Example : NumberHandler.gcd(48, 18)6
  • lcm(a: number, b: number): number Calculates the least common multiple. Example : NumberHandler.lcm(12, 18)36
  • gcdArray(numbers: number[]): number Calculates the GCD of an array. Example : NumberHandler.gcdArray([48, 18, 12])6
  • lcmArray(numbers: number[]): number Calculates the LCM of an array. Example : NumberHandler.lcmArray([12, 18])36
  • sumOfDigits(value: number): number Calculates the sum of digits. Example : NumberHandler.sumOfDigits(123)6
  • reverseDigits(value: number): number Reverses the digits of a number. Example : NumberHandler.reverseDigits(123)321
  • countDigits(value: number): number Counts the number of digits. Example : NumberHandler.countDigits(12345)5
  • nextPower(value: number, base: number): number Finds the next power of a base. Example : NumberHandler.nextPower(10, 2)16
  • absoluteDifference(a: number, b: number): number Calculates the absolute difference. Example : NumberHandler.absoluteDifference(10, 7)3

Number Formatting

  • toPercentage(value: number, decimals: number): string Converts to a percentage string. Example : NumberHandler.toPercentage(0.875, 1)"87.5%"
  • formatWithCommas(value: number): string Adds thousand separators. Example : NumberHandler.formatWithCommas(1000000)"1,000,000"
  • formatCurrency(value: number, currency: string, locale: string): string Formats as currency. Example : NumberHandler.formatCurrency(1234.56)"$1,234.56"
  • toScientific(value: number, decimals: number): string Formats in scientific notation. Example : NumberHandler.toScientific(12345, 2)"1.23e+4"
  • padWithZeros(value: number, length: number): string Pads with leading zeros. Example : NumberHandler.padWithZeros(7, 3)"007"
  • toBinary(value: number): string Converts to a binary string. Example : NumberHandler.toBinary(10)"1010"
  • toHex(value: number): string Converts to a hexadecimal string. Example : NumberHandler.toHex(255)"ff"
  • toRoman(value: number): string Converts to a Roman numeral. Example : NumberHandler.toRoman(2023)"MMXXIII"
  • toOrdinal(value: number): string Converts to ordinal form. Example : NumberHandler.toOrdinal(3)"3rd"
  • toOrdinalWords(value: number): string Converts to ordinal words. Example : NumberHandler.toOrdinalWords(3)"third"
  • toWords(value: number): string Converts to word representation. Example : NumberHandler.toWords(42)"forty-two"
  • toBase(value: number, base: number): string Converts to a specific base. Example : NumberHandler.toBase(15, 16)"f"
  • abbreviateNumber(value: number, decimals: number): string Abbreviates with units (k, M, B). Example : NumberHandler.abbreviateNumber(1500000, 1)"1.5M"
  • toSignificantDigits(value: number, digits: number): number Formats with significant digits. Example : NumberHandler.toSignificantDigits(123.456, 3)123

Statistical Operations

  • sum(numbers: number[]): number Calculates the sum of an array. Example : NumberHandler.sum([1, 2, 3])6
  • average(numbers: number[]): number Calculates the average. Example : NumberHandler.average([2, 4, 6])4
  • product(numbers: number[]): number Calculates the product. Example : NumberHandler.product([2, 3, 4])24
  • max(numbers: number[]): number Finds the maximum value. Example : NumberHandler.max([1, 5, 3])5
  • min(numbers: number[]): number Finds the minimum value. Example : NumberHandler.min([1, 5, 3])1
  • median(numbers: number[]): number Calculates the median. Example : NumberHandler.median([1, 3, 5])3
  • standardDeviation(numbers: number[]): number Calculates the standard deviation. Example : NumberHandler.standardDeviation([2, 4, 6])~1.414
  • variance(numbers: number[]): number Calculates the variance. Example : NumberHandler.variance([2, 4, 6])~2.667
  • sumOfSquares(numbers: number[]): number Calculates the sum of squares. Example : NumberHandler.sumOfSquares([2, 3])13
  • sumOfPowers(numbers: number[], power: number): number Calculates the sum of powers. Example : NumberHandler.sumOfPowers([2, 3], 2)13
  • harmonicMean(numbers: number[]): number Calculates the harmonic mean. Example : NumberHandler.harmonicMean([2, 3, 4])~2.77
  • mode(numbers: number[]): number Finds the most frequent value. Example : NumberHandler.mode([1, 2, 2, 3])2
  • weightedAverage(numbers: number[], weights: number[]): number Calculates the weighted average. Example : NumberHandler.weightedAverage([1, 2, 3], [0.2, 0.3, 0.5])2.3
  • arithmeticSum(start: number, end: number, n: number): number Calculates the sum of an arithmetic sequence. Example : NumberHandler.arithmeticSum(1, 5, 5)15
  • geometricSum(firstTerm: number, ratio: number, n: number): number Calculates the sum of a geometric sequence. Example : NumberHandler.geometricSum(2, 2, 3)14

Random Number Generation

  • randomInt(min: number, max: number): number Generates a random integer. Example : NumberHandler.randomInt(1, 5)e.g., 3
  • randomFloat(min: number, max: number): number Generates a random float. Example : NumberHandler.randomFloat(1, 5)e.g., 3.456
  • randomNormal(mean: number, stdDev: number): number Generates a random number from a normal distribution. Example : NumberHandler.randomNormal(0, 1)e.g., 0.234
  • randomNormalInt(mean: number, stdDev: number): number Generates a random integer from a normal distribution. Example : NumberHandler.randomNormalInt(0, 1)e.g., 0
  • randomExponential(rate: number): number Generates a random number from an exponential distribution. Example : NumberHandler.randomExponential(1)e.g., 0.693
  • uniqueRandomInts(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): number Converts degrees to radians. Example : NumberHandler.toRadians(180)~3.142
  • toDegrees(radians: number): number Converts radians to degrees. Example : NumberHandler.toDegrees(Math.PI)180
  • cosDegrees(degrees: number): number Calculates the cosine of an angle in degrees. Example : NumberHandler.cosDegrees(0)1
  • sinDegrees(degrees: number): number Calculates the sine of an angle in degrees. Example : NumberHandler.sinDegrees(90)1
  • tanDegrees(degrees: number): number Calculates the tangent of an angle in degrees. Example : NumberHandler.tanDegrees(45)1
  • acosDegrees(value: number): number Calculates the inverse cosine in degrees. Example : NumberHandler.acosDegrees(1)0
  • asinDegrees(value: number): number Calculates the inverse sine in degrees. Example : NumberHandler.asinDegrees(0)0
  • atanDegrees(value: number): number Calculates the inverse tangent in degrees. Example : NumberHandler.atanDegrees(1)45
  • angleBetweenPoints(x1: number, y1: number, x2: number, y2: number): number Calculates the angle between two points in degrees. Example : NumberHandler.angleBetweenPoints(0, 0, 1, 1)45

Geometric Operations

  • hypot(a: number, b: number): number Calculates the hypotenuse of a right triangle. Example : NumberHandler.hypot(3, 4)5
  • distance2D(x1: number, y1: number, x2: number, y2: number): number Calculates the Euclidean distance in 2D. Example : NumberHandler.distance2D(0, 0, 3, 4)5
  • distance3D(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number): number Calculates the Euclidean distance in 3D. Example : NumberHandler.distance3D(0, 0, 0, 1, 1, 1)~1.732
  • manhattanDistance(x1: number, y1: number, x2: number, y2: number): number Calculates the Manhattan distance in 2D. Example : NumberHandler.manhattanDistance(0, 0, 3, 4)7
  • midpoint(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): number Converts a numeric string to a number. Example : NumberHandler.parseNumber("123.45")123.45
  • range(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): number Calculates the logarithm with a specified base. Example : NumberHandler.log(100, 10)2
  • sign(value: number): number Returns the sign of a number. Example : NumberHandler.sign(-5)-1
  • percentageChange(oldValue: number, newValue: number): number Calculates 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 image
  • cropImage(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 image
  • rotateImage(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 image
  • flipHorizontal(input: string | Blob): Promise<string> Flips an image horizontally. Example : ImageHandler.flipHorizontal(base64Image) → Base64 string of flipped image
  • flipVertical(input: string | Blob): Promise<string> Flips an image vertically. Example : ImageHandler.flipVertical(base64Image) → Base64 string of flipped image
  • addBorder(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 image
  • addRoundedCorners(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 image
  • mergeImages(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 image
  • addDropShadow(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 image
  • extractROI(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 image
  • toBlob(input: string | Blob, format: string, quality?: number): Promise<Blob> Converts an image to a Blob. Example : ImageHandler.toBlob(base64Image, "image/jpeg") → Blob of JPEG image
  • base64ToBlob(base64: string, contentType: string): Promise<Blob> Converts a base64 string to a Blob. Example : ImageHandler.base64ToBlob(base64Image, "image/jpeg") → Blob of image
  • toWebP(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 image
  • compressImage(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)true
  • getDominantColor(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)true
  • getFileSize(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 image
  • adjustBrightness(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 image
  • adjustContrast(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 image
  • applyBlur(input: string | Blob, radius: number): Promise<string> Applies a blur effect to an image. Example : ImageHandler.applyBlur(base64Image, 5) → Base64 string of blurred image
  • applySepia(input: string | Blob): Promise<string> Applies a sepia effect to an image. Example : ImageHandler.applySepia(base64Image) → Base64 string of sepia image
  • adjustSaturation(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 image
  • invertColors(input: string | Blob): Promise<string> Inverts the colors of an image. Example : ImageHandler.invertColors(base64Image) → Base64 string of inverted image
  • applyVignette(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 image
  • sharpenImage(input: string | Blob, intensity?: number): Promise<string> Increases the sharpness of an image. Example : ImageHandler.sharpenImage(base64Image, 0.5) → Base64 string of sharpened image
  • detectEdges(input: string | Blob): Promise<string> Detects edges in an image using a Sobel filter. Example : ImageHandler.detectEdges(base64Image) → Base64 string of edge-detected image
  • rotateHue(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 image
  • posterize(input: string | Blob, levels?: number): Promise<string> Applies a posterize effect by reducing color levels. Example : ImageHandler.posterize(base64Image, 4) → Base64 string of posterized image
  • applyEmboss(input: string | Blob): Promise<string> Applies an emboss effect to an image. Example : ImageHandler.applyEmboss(base64Image) → Base64 string of embossed image
  • pixelate(input: string | Blob, pixelSize?: number): Promise<string> Applies a pixelation effect to an image. Example : ImageHandler.pixelate(base64Image, 10) → Base64 string of pixelated image
  • applyColorTint(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 image
  • reduceNoise(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 image
  • applyWatermark(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 image
  • createThumbnail(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 thumbnail
  • generatePreview(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): boolean Checks if a value is a non-empty plain object. Example : ObjectHandler.isNonEmptyObject({ a: 1 })true Example : ObjectHandler.isNonEmptyObject({})false
  • hasSameKeys(obj1: Record<string, any>, obj2: Record<string, any>): boolean Checks if two objects have the same keys. Example : ObjectHandler.hasSameKeys({ a: 1, b: 2 }, { a: 3, b: 4 })true
  • isSubset(subset: Record<string, any>, superset: Record<string, any>): boolean Checks if one object is a subset of another. Example : ObjectHandler.isSubset({ a: 1 }, { a: 1, b: 2 })true
  • hasAllKeys(obj: Record<string, any>, keys: string[]): boolean Checks if an object contains all specified keys. Example : ObjectHandler.hasAllKeys({ a: 1, b: 2 }, ['a', 'b'])true
  • matchesTemplate(obj: Record<string, any>, template: Record<string, any>): boolean Checks if an object matches a partial template. Example : ObjectHandler.matchesTemplate({ a: 1, b: 2 }, { a: 1 })true
  • hasOnlyTypes(obj: Record<string, any>, types: string[]): boolean Checks if an object contains only specified types for its values. Example : ObjectHandler.hasOnlyTypes({ a: 'x', b: 'y' }, ['string'])true
  • hasNestedObjects(obj: Record<string, any>): boolean Checks if an object contains nested objects. Example : ObjectHandler.hasNestedObjects({ a: { b: 1 } })true
  • validateSchema(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): boolean Checks if an object contains a specific value. Example : ObjectHandler.containsValue({ a: 1 }, 1)true
  • getTypeSummary(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): U Reduces an object to a single value using a callback. Example : ObjectHandler.reduceObject({ a: 1, b: 2 }, (acc, v) => acc + v, 0)3
  • sortByValues(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): boolean Checks if a value is a valid Date object. Example : DateTimeHandler.isValidDate(new Date())true
  • isInRange(date: Date, start: Date, end: Date): boolean Checks 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'))true
  • isSameDay(date1: Date, date2: Date): boolean Checks if two Dates are on the same day. Example : DateTimeHandler.isSameDay(new Date('2025-07-25'), new Date('2025-07-25'))true
  • isLeapYear(year: number): boolean Checks if a year is a leap year. Example : DateTimeHandler.isLeapYear(2024)true
  • isWeekend(date: Date): boolean Checks if a Date is a weekend day (Saturday or Sunday). Example : DateTimeHandler.isWeekend(new Date('2025-07-26'))true
  • isInMonth(date: Date, month: number): boolean Checks if a Date falls in a specific month. Example : DateTimeHandler.isInMonth(new Date('2025-07-25'), 6)true
  • **`isInYear(date: Date, yea