@hichchi/utils
v0.0.9
Published
A comprehensive utility library with essential helper functions for JavaScript/TypeScript applications
Downloads
1,072
Readme
🛠️ @hichchi/utils
Description
A comprehensive utility library with essential helper functions for JavaScript/TypeScript applications
Part of the Hichchi ecosystem - A powerful, scalable application built with Nx workspace
📋 Table Of Contents
- 📦 Installation
- ⚡ Quick Start
- 📋 Prerequisites
- 🌟 Overview
- ✨ Features
- 🛠️ Troubleshooting
- 🔧 Development
- 📖 API Documentation
📦 Installation
npm install @hichchi/utils⚡ Quick Start
Get up and running with powerful utility functions in just a few minutes:
// 1. Install the package
npm install @hichchi/utils
// 2. Import utility functions
import { dottedPathObjectToNested } from '@hichchi/utils';
// 3. Use utility functions in your application
const nestedObject = dottedPathObjectToNested({
"id": 123,
"name": "John Doe",
"profile.age": 30,
"profile.address.city": "New York",
"profile.address.zip": "10001"
});
Result:
// {
// id: 123,
// name: "John Doe",
// profile: {
// age: 30,
// address: {
// city: "New York",
// zip: "10001"
// }
// }
// }
📋 Prerequisites
Before installing @hichchi/utils, ensure you have:
Required Dependencies
- Node.js: ^18.0.0
- TypeScript: ^5.0.0 (for TypeScript projects)
🌟 Overview
🎯 Your essential toolkit for JavaScript and TypeScript development. From string manipulation to file operations, from object utilities to URL handling - everything you need to streamline your development workflow with battle-tested, performance-optimized utility functions.
✨ Features
🔤 String Utilities
- 🎨 Case Conversion - camelCase, PascalCase, snake_case, kebab-case transformations
- 🔍 String Analysis - Pattern matching, validation, and content analysis
- ✂️ String Manipulation - Truncation, padding, cleaning, and formatting
- 🏷️ Slug Generation - URL-friendly string generation with customizable options
- 📝 Template Processing - Advanced string templating with variable substitution
🗂️ Object Utilities
- 🔄 Deep Operations - Deep merge, clone, compare, and transformation
- 🎯 Property Access - Safe property getting/setting with dot notation
- 🔍 Object Analysis - Type checking, validation, and structure analysis
- 📊 Data Transformation - Object flattening, nesting, and restructuring
- 🧹 Object Cleaning - Remove null/undefined values, empty objects
📝 String Template Utilities
- 🎨 Template Processing - Advanced string templating with variable substitution
- 🔄 Dynamic Content - Apply templates with custom prefixes and transformations
- 🏷️ Tag-based Processing - Support for various template tags and formats
🌐 URL Utilities
- 🔒 Redirect Validation - Secure redirect URL validation against allowed domains
- 🛡️ Security Features - Prevent open redirect vulnerabilities
✅ Assertion Utilities
- 🔍 Type Guards - TypeScript type guards for arrays and objects
- 🎯 Property Checking - Check if objects have specific properties
- 🛡️ Safe Type Narrowing - Runtime type validation with TypeScript support
🎨 Developer Experience
- 📝 Full TypeScript Support - Complete type definitions and IntelliSense
- 🔧 Tree Shaking - Import only what you need for optimal bundle size
- 📚 Comprehensive Documentation - Detailed JSDoc comments for all functions
- 🧪 Well Tested - Extensive test coverage for reliability
- 🚀 Performance Optimized - Efficient algorithms and minimal overhead
🔒 Security Best Practices
Detailed security best practices will be added here
🛠️ Troubleshooting
Common Issues
TypeScript Compilation Issues
# Ensure you have the correct TypeScript version
npm install typescript@^5.0.0 --save-dev🔧 Development
Building the Library
nx build utilsRunning Tests
nx test utilsLinting
nx lint utilsPerformance Testing
nx run utils:benchmarkMade with ❤️ by Hichchi Dev
Building the future of development utilities, one commit at a time
📖 API Documentation
Complete technical reference for all classes, interfaces, methods, and types in this library.
Auto-generated by TypeDoc - Browse through detailed API references, code examples, and implementation guides below.
📋 API Table of Contents
- Enumerations
- Functions
- applyTemplate()
- applyTemplates()
- breakToWords()
- countOccurrences()
- createExcerpt()
- deepCopy()
- dottedPathObjectToNested()
- escapeRegExp()
- extractEmails()
- extractUrls()
- filterByObject()
- format()
- getEnumValues()
- getFileExt()
- getFileSize()
- getMapKey()
- getMapKeys()
- getValueByPath()
- groupBy()
- hashString()
- hasOwnAll()
- htmlToText()
- isAlphanumeric()
- isArray()
- isObject()
- isObjectWith()
- isValidRedirectUrl()
- maskString()
- normalizeString()
- objectToDottedPathValueObject()
- omit()
- padString()
- plural()
- prune()
- randomString()
- removeWhitespace()
- reverse()
- searchMapValues()
- singular()
- slugify()
- stringSimilarity()
- toCamelCase()
- toFirstCase()
- toFirstCaseBreak()
- toKebabCase()
- toLowerCase()
- toLowerCaseBreak()
- toNumber()
- toPascalCase()
- toProperTitleCase()
- toSentenceCase()
- toSnakeCase()
- toTitleCase()
- toUpperCase()
- toUpperCaseBreak()
- truncate()
- wordWrap()
- Interfaces
- Type Aliases
- Variables
Enumerations
TemplateTag
Defined in: enums/template-tag.enum.ts:15
Template tags for string transformations
This enum defines all available template tags that can be used with the applyTemplate
and applyTemplates functions. Each tag corresponds to a specific string transformation
function from the string.utils module.
Template tags are represented as strings in the format #{transformationName}. When these
tags appear in template strings, they are replaced with the result of applying the
corresponding transformation to the provided value.
See
- applyTemplate For applying a single value to a template
- applyTemplates For applying multiple values to a template
Enumeration Members
CAMEL_CASE
"#{camelCase}"
FIRST_CASE
"#{firstCase}"
FIRST_CASE_BREAK
"#{firstCaseBreak}"
HTML_TO_TEXT
"#{htmlToText}"
KEBAB_CASE
"#{kebabCase}"
LOWER_CASE
"#{lowerCase}"
LOWER_CASE_BREAK
"#{lowerCaseBreak}"
NUMBER
"#{number}"
PASCAL_CASE
"#{pascalCase}"
SENTENCE_CASE
"#{sentenceCase}"
SINGULAR
"#{singular}"
SNAKE_CASE
"#{snakeCase}"
TITLE_CASE
"#{titleCase}"
UPPER_CASE
"#{upperCase}"
UPPER_CASE_BREAK
"#{upperCaseBreak}"
UPPER_KEBAB_CASE
"#{upperKebabCase}"
UPPER_SNAKE_CASE
"#{upperSnakeCase}"
Functions
applyTemplate()
function applyTemplate(str, prefix): string;Defined in: utils/string-template.utils.ts:83
Applies a value to a template string containing transformation tags.
This function replaces template tags in a string with transformed versions of a provided value. It's particularly useful for creating dynamic messages, error notifications, or any text that needs to include the same value in different formats.
Each template tag is replaced with the result of applying the corresponding transformation function to the provided value. If a tag isn't present in the template string, that transformation is skipped.
Available template tags:
#{upperCase}- Converts to UPPERCASE ("USER")#{snakeCase}- Converts to snake_case ("user_profile")#{upperSnakeCase}- Converts to UPPER_SNAKE_CASE ("USER_PROFILE")#{lowerCase}- Converts to lowercase ("user")#{sentenceCase}- Converts to Sentence case ("User profile")#{firstCase}- Converts to First case ("User")#{camelCase}- Converts to camelCase ("userProfile")#{pascalCase}- Converts to PascalCase ("UserProfile")#{kebabCase}- Converts to kebab-case ("user-profile")#{upperKebabCase}- Converts to KEBAB-CASE ("USER-PROFILE")#{titleCase}- Converts to Title Case ("User Profile")#{lowerCaseBreak}- Breaks words and converts to lowercase ("user profile")#{upperCaseBreak}- Breaks words and converts to UPPERCASE ("USER PROFILE")#{firstCaseBreak}- Breaks words and applies First case ("User profile")#{singular}- Converts plural to singular form ("users" → "user")#{number}- Converts to a number if possible ("123" → 123)#{htmlToText}- Removes HTML tags ("User" → "User")#{format}- Formats a string with placeholders (used with additional parameters)
Parameters
str
string
Template string containing transformation tags
prefix
string
The prefix to update with
Returns
string
- The template with all tags replaced by transformed values
Examples
// Error message with different versions of the same term
applyTemplate(
"Cannot create a #{lowerCase} with this email. #{sentenceCase} already exists.",
"User",
);
// Output: "Cannot create a user with this email. User already exists."// Using multiple transformations of the same value
applyTemplate(
"Model: #{pascalCase}\nTable: #{snakeCase}\nAPI Path: #{kebabCase}",
"blogPost",
);
// Output:
// Model: BlogPost
// Table: blog_post
// API Path: blog-postSee
- TemplateTag For the full list of available template tags
- applyTemplates For applying multiple different values to a template
applyTemplates()
function applyTemplates(str, prefixes): string;Defined in: utils/string-template.utils.ts:211
Applies multiple named template transformations to a string with different values for each prefix.
This advanced templating function allows you to use multiple different values within a single
template string, each with their own set of transformation tags. Unlike applyTemplate which
applies one value to all tags, this function lets you specify different values for different
prefixes, enabling complex template scenarios with multiple entities.
Each prefix in the template is identified by a namespace (e.g., user, post) followed by
a dot and the transformation tag (e.g., #{user.lowerCase}, #{post.titleCase}). This allows
for sophisticated template generation where different parts of the text need different source
values with various transformations applied.
This is particularly useful for generating complex messages, code templates, documentation, or any text that involves multiple entities that need to be formatted differently within the same template.
Parameters
str
string
Template string containing namespaced transformation tags in the format
#{prefix.transformationType} where prefix matches keys in the prefixes object
prefixes
Record<string, string>
Object mapping prefix names to their corresponding values. Each key becomes a namespace in the template, and the value is the string that will be transformed according to the tags.
Returns
string
The template string with all namespaced tags replaced by their transformed values
Examples
// Multi-entity message generation
const message = applyTemplates(
'User #{user.lowerCase} created a new #{entity.sentenceCase} titled "#{title.titleCase}"',
{
user: "JohnDoe",
entity: "blogPost",
title: "my first programming tutorial",
},
);
// Returns: "User johndoe created a new Blog post titled "My First Programming Tutorial""// Code generation with multiple entities
const codeTemplate = applyTemplates(
`class #{model.pascalCase} {
constructor(private #{service.camelCase}: #{service.pascalCase}Service) {}
async create#{model.pascalCase}(data: #{model.pascalCase}Data): Promise<#{model.pascalCase}> {
return this.#{service.camelCase}.create(data);
}
}`,
{
model: "user-profile",
service: "database",
},
);
// Generates a complete class with proper naming conventions// API documentation generation
const apiDoc = applyTemplates(
`## #{endpoint.titleCase}
**URL:** \`/api/#{endpoint.kebabCase}\`
**Method:** #{method.upperCase}
**Model:** #{model.pascalCase}
Creates a new #{model.lowerCaseBreak} in the system.`,
{
endpoint: "userProfiles",
method: "post",
model: "UserProfile",
},
);// Database migration script generation
const migration = applyTemplates(
`CREATE TABLE #{table.snakeCase} (
id SERIAL PRIMARY KEY,
#{field.snakeCase} VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_#{table.snakeCase}_#{field.snakeCase} ON #{table.snakeCase}(#{field.snakeCase});`,
{
table: "UserProfiles",
field: "emailAddress",
},
);Remarks
- Each prefix in the prefixes object becomes a namespace in the template
- Template tags must follow the format
#{prefix.transformationType} - All transformation types available in
applyTemplateare supported - If a prefixed tag is not found in the template, it's simply ignored
- The function processes all prefixes and their transformations in the order they appear
- Supports the same transformation types as the TemplateTag enum
- More flexible than
applyTemplatebut with slightly more complex syntax
See
- applyTemplate For applying a single value to multiple transformation tags
- TemplateTag For the complete list of available transformation types
breakToWords()
Call Signature
function breakToWords(str): string[];Defined in: utils/string.utils.ts:47
Breaks a string into an array of words based on common separator patterns.
This function intelligently splits strings into individual words by detecting various word boundary patterns, including:
- Camel case boundaries ("helloWorld" → ["hello", "world"])
- Snake case boundaries ("hello_world" → ["hello", "world"])
- Kebab case boundaries ("hello-world" → ["hello", "world"])
- Space-separated words ("hello world" → ["hello", "world"])
- Uppercase acronyms ("APIClient" → ["api", "client"])
The returned words are all converted to lowercase.
Parameters
str
string
The string to split into words
Returns
string[]
- An array of lowercase words
Example
breakToWords("helloWorld"); // ['hello', 'world']
breakToWords("hello_world"); // ['hello', 'world']
breakToWords("hello-world"); // ['hello', 'world']
breakToWords("hello world"); // ['hello', 'world']
breakToWords("APIConfig"); // ['api', 'config']
breakToWords("123Test456"); // ['123', 'test', '456']Remarks
- Returns an empty array for empty, null, or undefined input
- Preserves numbers as separate words
- Handles consecutive uppercase letters as acronyms (preserving them as a single word)
Call Signature
function breakToWords(str, format): string;Defined in: utils/string.utils.ts:76
Breaks a string into words and formats them using a provided function.
This overload splits a string into words using the same logic as the array version, but additionally applies a formatting function to each word and joins them with spaces.
Common use cases include:
- Converting camelCase to Title Case
- Formatting identifiers for display
- Normalizing different string formats
Parameters
str
string
The string to split and format
format
(str) => string
A function to apply to each word
Returns
string
- A space-joined string of formatted words
Example
// Convert camelCase to Sentence case
breakToWords("helloWorld", toFirstCase); // "Hello world"
// Convert snake_case to Title Case
breakToWords("user_profile_data", toFirstCase); // "User profile data"
// Format with a custom function
breakToWords("SYSTEM_ERROR", (word) => word.toLowerCase()); // "system error"countOccurrences()
function countOccurrences(str, searchValue, caseSensitive?): number;Defined in: utils/string.utils.ts:1288
Counts the occurrences of a substring within a string.
Parameters
str
string
undefined
The string to search within
searchValue
string
undefined
The substring to search for
caseSensitive?
boolean
true
Whether the search should be case-sensitive
Returns
number
- The number of occurrences
Example
countOccurrences("hello hello world", "hello"); // 2
countOccurrences("Hello hello", "hello", false); // 2
countOccurrences("Hello hello", "hello", true); // 1createExcerpt()
function createExcerpt(text, searchTerm, contextLength?, ellipsis?): string;Defined in: utils/string.utils.ts:721
Creates an excerpt from a longer text by extracting a portion around a search term. Useful for search result highlighting or previews.
Parameters
text
string
undefined
The full text to create an excerpt from
searchTerm
string
undefined
The search term to find in the text
contextLength?
number
DEFAULT_CONTEXT_LENGTH
Number of characters to include before and after the search term
ellipsis?
string
DEFAULT_ELLIPSIS
Characters to use for indicating truncated text
Returns
string
- The excerpt with the search term in context
Example
const article =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris.";
createExcerpt(article, "dolor", 10);
// "...ipsum dolor sit amet..."
createExcerpt(article, "consectetur", 15, "[...]");
// "[...]sit amet, consectetur adipiscing[...]"deepCopy()
function deepCopy<T>(obj): T;Defined in: utils/object.utils.ts:23
Deep copy an object.
Type Parameters
T
Type of the object.
Parameters
obj
T
Object to copy.
Returns
T
Copied object.
Example
// Example usage
const object = {
name: "John Doe"
}
const copiedObject = deepCopy(object);dottedPathObjectToNested()
function dottedPathObjectToNested<R>(pathValueSet): R;Defined in: utils/object.utils.ts:549
Converts a flattened DottedPathValueObject back into a nested object structure.
This function is the inverse of objectToDottedPathValueObject. It takes a flat map of
dot-notation paths to values and reconstructs a hierarchical object structure.
Each key in the input DottedPathValueObject represents a path through the object hierarchy, with dots separating each level. The function builds a nested object structure by parsing these paths and placing values at the appropriate locations.
Type Parameters
R
object
The type of the returned object (defaults to object)
Parameters
pathValueSet
Record<string, any>
A flattened object with dot-notation path keys
Returns
R
- A reconstructed nested object with the original hierarchy
Remarks
- Paths are validated for safety to prevent injection attacks
- Invalid paths are silently skipped (not included in the result)
- Path components should contain only alphanumeric characters, underscores, hyphens, and dots
See
- objectToDottedPathValueObject The inverse operation to convert an object to DottedPathValueObject
- DottedPathValueObject The interface for the input flattened object
Examples
// Convert a flat DottedPathValueObject to a nested object
const flatData = {
"id": 123,
"name": "John Doe",
"profile.age": 30,
"profile.address.city": "New York",
"profile.address.zip": "10001"
};
const nestedObject = dottedPathObjectToNested(flatData);
Result:
// {
// id: 123,
// name: "John Doe",
// profile: {
// age: 30,
// address: {
// city: "New York",
// zip: "10001"
// }
// }
// }// Typed return value
interface User {
id: number;
name: string;
profile: {
age: number;
address: {
city: string;
zip: string;
};
};
}
const userData = dottedPathObjectToNested<User>(flatData);
// Returns object with User typeescapeRegExp()
function escapeRegExp(str): string;Defined in: utils/string.utils.ts:1134
Escapes special characters in a string for use in regular expressions.
Parameters
str
string
The string to escape
Returns
string
- The escaped string safe for use in RegExp
Example
escapeRegExp("hello.world*"); // "hello\.world\*"
// Usage in RegExp:
const userInput = "hello.world*";
const regex = new RegExp(escapeRegExp(userInput));extractEmails()
function extractEmails(str): string[];Defined in: utils/string.utils.ts:456
Extracts all email addresses from a string.
Parameters
str
string
The string to extract emails from
Returns
string[]
- Array of found email addresses
Example
extractEmails("Contact us at [email protected] or [email protected]");
// ["[email protected]", "[email protected]"]extractUrls()
function extractUrls(str): string[];Defined in: utils/string.utils.ts:475
Extracts all URLs from a string.
Parameters
str
string
The string to extract URLs from
Returns
string[]
- Array of found URLs
Example
extractUrls("Visit https://example.com or http://test.org/page?id=5");
// ["https://example.com", "http://test.org/page?id=5"]filterByObject()
function filterByObject<T>(items, filters): T[];Defined in: utils/object.utils.ts:1082
Filters items by recursively matching nested property values.
Type Parameters
T
Parameters
items
T[]
filters
Returns
T[]
format()
Implementation of the format function that handles both overloads.
Call Signature
function format(template, ...values): string;Defined in: utils/string.utils.ts:1220
Formats a string by replacing indexed placeholders with provided values.
This implementation uses {n} syntax for indexed placeholders where n is the position of the value in the arguments list (0-based).
Parameters
template
string
The template string with {0}, {1}, etc. placeholders
...values
(string | number | boolean | null | undefined)[]
Values to insert into the template
Returns
string
- The formatted string
Example
format("Hello, {0}!", "World"); // "Hello, World!"
format("User {0} has {1} points", "John", 100);
// "User John has 100 points"Call Signature
function format(template, values): string;Defined in: utils/string.utils.ts:1239
Formats a string by replacing named placeholders with values from an object.
This implementation uses {name} syntax for named placeholders where 'name' corresponds to a property in the provided values object.
Parameters
template
string
The template string with {propertyName} placeholders
values
Record<string, string | number | boolean | null | undefined>
Object with values to insert
Returns
string
- The formatted string
Example
// Named placeholders with object
format("Hello, {name}! You have {count} messages.", {
name: "Alice",
count: 5,
});
// "Hello, Alice! You have 5 messages."getEnumValues()
function getEnumValues<T>(e): T[keyof T][];Defined in: utils/object.utils.ts:1070
Extracts all values from a TypeScript enum, handling both string and numeric enum types correctly.
This utility function safely retrieves the actual values from TypeScript enums, accounting for the different internal representations of string and numeric enums. For numeric enums, TypeScript creates reverse mappings (value → key), so this function filters out the reverse mapping entries to return only the actual enum values. For string enums, it returns all values directly.
This is particularly useful when you need to iterate over enum values, validate input against enum values, create dropdown options from enums, or perform any operation that requires access to the actual enum values rather than the keys.
Type Parameters
T extends object
The enum type extending object
Parameters
e
T
The enum object to extract values from
Returns
T[keyof T][]
An array containing all the actual values of the enum
Examples
// String enum example
enum Color {
RED = "red",
GREEN = "green",
BLUE = "blue",
}
const colorValues = getEnumValues(Color);
// Returns: ["red", "green", "blue"]
// Use for validation
function isValidColor(value: string): value is Color {
return getEnumValues(Color).includes(value as Color);
}// Numeric enum example
enum Status {
PENDING, // 0
APPROVED, // 1
REJECTED, // 2
}
const statusValues = getEnumValues(Status);
// Returns: [0, 1, 2] (not ["PENDING", "APPROVED", "REJECTED", 0, 1, 2])
// Use for creating select options
const statusOptions = getEnumValues(Status).map((value) => ({
value,
label: Status[value], // Get the key name for display
}));// Mixed numeric enum example
enum HttpStatus {
OK = 200,
NOT_FOUND = 404,
SERVER_ERROR = 500,
}
const httpStatusValues = getEnumValues(HttpStatus);
// Returns: [200, 404, 500]
// Use for status code validation
function isValidHttpStatus(code: number): code is HttpStatus {
return getEnumValues(HttpStatus).includes(code as HttpStatus);
}// Creating dropdown options from enum
enum UserRole {
ADMIN = "admin",
USER = "user",
MODERATOR = "moderator",
}
const roleOptions = getEnumValues(UserRole).map((role) => ({
value: role,
label: role.charAt(0).toUpperCase() + role.slice(1),
}));
// Returns: [
// { value: "admin", label: "Admin" },
// { value: "user", label: "User" },
// { value: "moderator", label: "Moderator" }
// ]Remarks
- Automatically detects numeric vs string enums and handles them appropriately
- For numeric enums, filters out reverse mapping entries that TypeScript automatically creates
- For string enums, returns all values as-is since there are no reverse mappings
- Works with mixed numeric enums (enums with explicit numeric values)
- The returned array maintains the order of enum declaration
- Type-safe: the return type is correctly inferred as an array of the enum's value types
See
Object.values The underlying method used to extract enum entries
getFileExt()
function getFileExt(mimeType, allowedMimeTypes?): string | undefined;Defined in: utils/file.utils.ts:1265
Get the file extension of the given mime type.
Parameters
mimeType
string
Mime type.
allowedMimeTypes?
Map<string, string>
Allowed mime types. If not provided, the default mime types map will be used.
Returns
string | undefined
File extension or undefined if the mime type is not found.
Examples
// Using the default mime types map
const extension = getFileExt('application/pdf');
// Output: 'pdf'// Using a custom mime types map
const customMimeTypes = new Map([
['jpg', 'image/jpeg'],
['png', 'image/png']
]);
const extension = getFileExt('image/jpeg', customMimeTypes);
// Output: 'jpg'getFileSize()
function getFileSize(size, round?): string;Defined in: utils/file.utils.ts:1296
Get file size in human-readable format.
Parameters
size
number
File size in bytes.
round?
boolean
Whether to round the size to whole numbers. If true, decimals will be removed.
Returns
string
File size in human-readable format (B, KB, MB, or GB).
Examples
// Get file size with decimals
const readableSize = getFileSize(1536);
// Output: '1.50 KB'// Get rounded file size
const roundedSize = getFileSize(1536, true);
// Output: '2 KB'// Get size for larger files
const largeFileSize = getFileSize(1073741824);
// Output: '1.00 GB'getMapKey()
function getMapKey(map, value): string | undefined;Defined in: utils/object.utils.ts:53
Get the key of a map by value.
Parameters
map
Map<string, unknown>
Map to get key from.
value
unknown
Value to get key for.
Returns
string | undefined
Key of the map.
Example
// Example usage
const user = new Map<string, string>([
["firstName", "John"],
["lastName", "Doe"],
["preferredName", "John"],
["age", 30],
]);
const key = getMapKey(user, "value2");
// Example output: "firstName"getMapKeys()
function getMapKeys(map, partialValue): string[];Defined in: utils/object.utils.ts:122
Retrieves all keys from a Map where the corresponding values contain a specified substring.
This utility function searches through a Map's values and returns an array of keys whose associated values include the provided partial string. The search is case-sensitive and uses JavaScript's native string.includes() method for matching.
This is particularly useful for implementing search functionality, filtering operations, or finding related entries in configuration maps, user preference stores, or any key-value data structure where you need to locate entries by partial value matching.
Parameters
map
Map<string, string>
The Map to search through for matching values
partialValue
string
The substring to search for within the Map's values
Returns
string[]
An array of keys whose corresponding values contain the partial value
Examples
// Search user preferences for entries containing "John"
const userPreferences = new Map<string, string>([
["displayName", "John Doe"],
["firstName", "John"],
["lastName", "Doe"],
["preferredName", "Johnny"],
["email", "[email protected]"],
]);
const johnKeys = getMapKeys(userPreferences, "John");
// Returns: ["displayName", "firstName", "email"]// Find configuration keys related to database settings
const config = new Map<string, string>([
["db_host", "localhost"],
["db_port", "5432"],
["cache_host", "redis-server"],
["db_name", "myapp_database"],
["log_level", "debug"],
]);
const dbKeys = getMapKeys(config, "db");
// Returns: ["db_name"] (only values containing "db", not keys)// Search in a translations map
const translations = new Map<string, string>([
["welcome_message", "Welcome to our application"],
["error_message", "An error occurred"],
["success_message", "Operation completed successfully"],
["info_message", "Please check your information"],
]);
const messageKeys = getMapKeys(translations, "message");
// Returns: ["welcome_message", "error_message", "success_message", "info_message"]Remarks
- The search is case-sensitive; "John" will not match "john"
- Returns an empty array if no matches are found
- The function iterates through all Map entries, so performance scales with Map size
- Only works with Maps that have string values; other value types will cause runtime errors
getValueByPath()
function getValueByPath<T>(obj, path): T | undefined;Defined in: utils/object.utils.ts:379
Gets a value from a nested object using a dot-notation path string.
This function safely traverses a deeply nested object structure using a string path with dot notation. It handles both object properties and array indices within the path.
Type Parameters
T
Type of the value to be returned.
Parameters
obj
The object to retrieve the value from.
path
string
The dot-notation path to the desired value.
- Use dots to navigate through nested objects: 'user.profile.address'
- Use array notation for accessing array elements: 'items[0]' or 'users[2].name'
Returns
T | undefined
- The value at the specified path, or undefined if:
- Any part of the path doesn't exist
- An array index is out of bounds
- The path format is invalid
Examples
// Simple nested object property
const user = {
profile: {
name: "John Doe",
contact: { email: "[email protected]" },
},
};
const email = getValueByPath<string>(user, "profile.contact.email");
// Returns: "[email protected]"// Accessing array elements
const data = {
users: [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
],
};
const name = getValueByPath<string>(data, "users[1].name");
// Returns: "Bob"groupBy()
function groupBy<K, V>(list, keyGetter): Map<K, V[]>;Defined in: utils/object.utils.ts:237
Groups an array of objects into a Map based on a key extraction function.
This utility function takes an array of objects and organizes them into groups based on a common key or property. The grouping is performed using a key extraction function that you provide, which determines how each object should be categorized. The result is a Map where each key represents a group and the value is an array of objects belonging to that group.
This is particularly useful for data analysis, reporting, organizing collections for display purposes, or preparing data for further processing where items need to be categorized by shared characteristics.
Type Parameters
K
The type of the grouping key (can be string, number, boolean, etc.)
V
The type of the objects being grouped
Parameters
list
V[]
The array of objects to group
keyGetter
(input) => K
A function that extracts the grouping key from each object. This function receives an object and should return the value to group by. If the function returns null or undefined, the object will be grouped under a null key.
Returns
Map<K, V[]>
A Map where keys are the grouping values and values are arrays of objects that share that grouping key
Examples
// Group users by age
interface User {
name: string;
age: number;
department: string;
}
const users: User[] = [
{ name: "John", age: 30, department: "Engineering" },
{ name: "Jane", age: 25, department: "Marketing" },
{ name: "Bob", age: 30, department: "Engineering" },
{ name: "Alice", age: 25, department: "Sales" },
{ name: "Charlie", age: 35, department: "Engineering" },
];
const usersByAge = groupBy(users, (user) => user.age);
// Returns:
// Map {
// 30 => [
// { name: "John", age: 30, department: "Engineering" },
// { name: "Bob", age: 30, department: "Engineering" }
// ],
// 25 => [
// { name: "Jane", age: 25, department: "Marketing" },
// { name: "Alice", age: 25, department: "Sales" }
// ],
// 35 => [
// { name: "Charlie", age: 35, department: "Engineering" }
// ]
// }// Group products by category
interface Product {
id: number;
name: string;
category: string;
price: number;
}
const products: Product[] = [
{ id: 1, name: "Laptop", category: "Electronics", price: 999 },
{ id: 2, name: "Book", category: "Education", price: 29 },
{ id: 3, name: "Phone", category: "Electronics", price: 699 },
{ id: 4, name: "Pen", category: "Office", price: 5 },
];
const productsByCategory = groupBy(products, (product) => product.category);
// Useful for creating category-based product listings// Group tasks by completion status with boolean keys
interface Task {
id: number;
title: string;
completed: boolean;
}
const tasks: Task[] = [
{ id: 1, title: "Review code", completed: true },
{ id: 2, title: "Write tests", completed: false },
{ id: 3, title: "Deploy app", completed: true },
{ id: 4, title: "Update docs", completed: false },
];
const tasksByStatus = groupBy(tasks, (task) => task.completed);
// Returns Map with boolean keys: true and falseRemarks
- The function preserves the original order of objects within each group
- If the keyGetter function returns null or undefined, those objects will be grouped under a null key
- The Map structure allows for efficient lookups and iteration over groups
- Works with any type of grouping key (string, number, boolean, objects, etc.)
- Empty arrays will return an empty Map
hashString()
function hashString(str): Promise<string>;Defined in: utils/string.utils.ts:499
Converts a string to a secure hash using SHA-256.
Note: This is a browser-compatible implementation using the Web Crypto API. For Node.js environments, you might want to use the crypto module instead.
Parameters
str
string
The string to hash
Returns
Promise<string>
- Promise resolving to the hex hash string
Example
// Browser usage
await hashString("password123");
// "ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f"hasOwnAll()
function hasOwnAll(obj, props): boolean;Defined in: utils/object.utils.ts:965
Checks if an object has all specified properties as its own properties (not inherited).
This utility function verifies that an object contains all the properties listed in the provided array as direct (own) properties, not inherited from the prototype chain. It uses the modern Object.hasOwn() method for reliable property existence checking, making it safer than using hasOwnProperty() directly.
This is particularly useful for validating object structures, ensuring required properties exist before processing, implementing type guards, or verifying that objects conform to expected interfaces. It's commonly used in data validation, API request validation, and ensuring objects have all necessary properties before performing operations.
Parameters
obj
Record<PropertyKey, unknown>
The object to check for property existence
props
PropertyKey[]
Array of property keys to verify exist on the object. PropertyKey includes string, number, and symbol types.
Returns
boolean
True if the object has all specified properties as own properties, false otherwise
Examples
// Validate that a user object has required properties
interface User {
id: number;
name: string;
email: string;
}
const user = {
id: 123,
name: "John Doe",
email: "[email protected]",
role: "admin",
};
const hasRequiredProps = hasOwnAll(user, ["id", "name", "email"]);
// Returns: true
const hasAllProps = hasOwnAll(user, ["id", "name", "email", "phone"]);
// Returns: false (missing 'phone' property)// Validate API request payload
function processUserUpdate(payload: unknown): User | null {
if (typeof payload === "object" && payload !== null) {
const requiredFields = ["id", "name", "email"];
if (hasOwnAll(payload as Record<string, unknown>, requiredFields)) {
// Safe to process as we know all required fields exist
return updateUser(payload as User);
}
}
throw new Error("Invalid payload: missing required fields");
}// Check configuration object completeness
interface DatabaseConfig {
host: string;
port: number;
database: string;
username: string;
password: string;
}
const config = {
host: "localhost",
port: 5432,
database: "myapp",
username: "admin",
// password is missing
};
const requiredConfigKeys = ["host", "port", "database", "username", "password"];
const isConfigComplete = hasOwnAll(config, requiredConfigKeys);
// Returns: false
if (!isConfigComplete) {
throw new Error("Database configuration is incomplete");
}// Work with symbol properties
const symbolKey = Symbol("secret");
const obj = {
name: "test",
[symbolKey]: "hidden value",
};
const hasSymbolProp = hasOwnAll(obj, ["name", symbolKey]);
// Returns: trueRemarks
- Uses Object.hasOwn() which is more reliable than hasOwnProperty()
- Only checks for own properties, not inherited properties from the prototype chain
- Returns false immediately if any property is missing (short-circuit evaluation)
- Works with string, number, and symbol property keys
- Returns true for an empty properties array (vacuous truth)
- Does not check property values, only existence
See
Object.hasOwn The underlying method used for property checking
htmlToText()
function htmlToText(str): string;Defined in: utils/string.utils.ts:1001
Remove HTML tags from a string and return plain text.
Parameters
str
string
String to remove HTML tags from.
Returns
string
Plain text.
Example
htmlToText("<h1>Hello World</h1>"); // "Hello World"isAlphanumeric()
function isAlphanumeric(str): boolean;Defined in: utils/string.utils.ts:1325
Checks if a string contains only alphanumeric characters.
Parameters
str
string
The string to check
Returns
boolean
- True if the string contains only alphanumeric characters
Example
isAlphanumeric("abc123"); // true
isAlphanumeric("abc-123"); // falseisArray()
function isArray<T>(value): value is T[];Defined in: utils/assertions.utils.ts:42
Type-safe utility to check if a value is an array of a specific type.
This function acts as a type guard that not only checks if the provided value is an array (using the native Array.isArray method), but also narrows the TypeScript type to an array of the generic type T. This enables safer handling of potentially array-typed values with full type inference in the conditional branches.
Type Parameters
T
The expected element type of the array
Parameters
value
T | T[] | undefined
The value to check, which could be a single item, an array of items, or undefined
Returns
value is T[]
Type predicate that narrows the type to T[] when true
Remarks
While this function essentially wraps Array.isArray, its value comes from the TypeScript type narrowing it provides, making it especially useful in code that needs to handle both single items and collections of items with type safety.
The function properly handles undefined values by returning false, making it safe to use with optional parameters or potentially undefined values.
Example
// Function that can accept either a single user or multiple users
async function createUser(
userOrUsers: UserDto | UserDto[] | undefined,
): Promise<User | User[]> {
// TypeScript knows userOrUsers is UserDto[] in this branch
if (isArray<UserDto>(userOrUsers)) {
return Promise.all(userOrUsers.map((user) => userService.createUser(user)));
}
// TypeScript knows userOrUsers is UserDto or undefined in this branch
else if (userOrUsers) {
return userService.createUser(userOrUsers);
} else {
throw new BadRequestException("User data is required");
}
}isObject()
function isObject<T>(value?): value is T;Defined in: utils/assertions.utils.ts:91
Type-safe utility to check if a value is a non-array object of a specific type.
This function serves as a type guard that checks if the provided value is an object (but not an array) and narrows the TypeScript type to the generic type T. It properly excludes null, arrays, and primitive values, focusing only on object instances.
Type Parameters
T
The expected object type to narrow to when the check passes
Parameters
value?
T | T[]
The value to check, which could be a single object, an array of objects, or undefined
Returns
value is T
Type predicate that narrows the type to T when true
Remarks
This function performs three checks to ensure the value is a proper object:
- It's not an array (using Array.isArray)
- It's of type "object" according to JavaScript's typeof operator
- It's not null (which would pass the typeof check but isn't a valid object)
This is particularly useful when handling parameters that could be either an object or a simpler identifier (like an ID), allowing for type-safe conditional logic.
Example
// Function that can accept either a user ID or a user object
async function getUserInfo(
userIdOrUser: number | User | undefined,
): Promise<UserInfo> {
// TypeScript knows userIdOrUser is User in this branch
if (isObject<User>(userIdOrUser)) {
// Can safely access object properties
return await userService.getUserInfo(userIdOrUser.id);
}
// TypeScript knows userIdOrUser is number or undefined in this branch
else {
return await userService.getUserInfo(userIdOrUser);
}
}
// Works with optional parameters too
function formatUserName(user?: User | string): string {
if (isObject<User>(user)) {
return `${user.firstName} ${user.lastName}`;
}
return user || "Guest";
}isObjectWith()
function isObjectWith<T>(value, propertyName): value is T;Defined in: utils/assertions.utils.ts:158
Type-safe utility to check if a value is an object with a specific property.
This function acts as a type guard that determines if an unknown value is an object that contains a specified property, and narrows the TypeScript type to the generic type T when true. This provides a robust way to implement duck typing in TypeScript, allowing for safe property access in the conditional branches.
Type Parameters
T extends object
The expected object type that should contain the property
Parameters
value
unknown
Any value to check, with no type constraints
propertyName
keyof T
The name of the property that should exist on the object
Returns
value is T
Type predicate that narrows the type to T when true
Remarks
This function uses Object.prototype.hasOwnProperty.call to safely check for property existence, even if the object has a custom implementation of hasOwnProperty or if the property is named 'hasOwnProperty'.
Unlike the simpler isObject utility, this function can distinguish between different object types based on their properties, making it ideal for discriminating between different interface implementations or handling union types.
Example
// Check if an object has the properties of a User interface
interface User {
id: number;
name: string;
}
interface Order {
orderNumber: string;
items: string[];
}
// Function that can handle different object types
function processEntity(entity: unknown): void {
// Check if entity has 'id' property, indicating it's a User
if (isObjectWith<User>(entity, "id")) {
// TypeScript knows entity is User in this branch
console.log(`Processing user: ${entity.name}`);
}
// Check if entity has 'order