In the world of modern web development, efficiency and code reusability are paramount. TypeScript, with its strong typing and robust features, empowers developers to build scalable and maintainable applications. A crucial aspect of this efficiency comes from a well-stocked arsenal of utility functions – small, focused pieces of code designed to perform common tasks.
This article presents 50 invaluable TypeScript utility functions that can streamline your development workflow, enhance code readability, and significantly boost your productivity. From handling arrays and objects to manipulating strings and dates, these utilities cover a broad spectrum of everyday programming challenges.
Let’s dive into these essential functions!
1. Mastering Random Number Generation
Explore how to effortlessly generate random integer numbers up to a specified maximum value. This function leverages Math.random()
to produce a floating-point number between 0 (inclusive) and 1 (exclusive), which is then scaled and floored to fit the desired range, ensuring a truly unpredictable outcome for various applications.
2. Verifying Object Emptiness
Discover a concise method to determine if a given JavaScript object contains any enumerable properties. By inspecting the length of the array returned by Object.keys()
, this utility efficiently checks for an empty object, proving invaluable for conditional logic and data validation.
3. Building a Dynamic Countdown Timer
Learn to implement a functional countdown timer that displays remaining time in minutes and seconds. This utility utilizes setInterval
to decrement a counter every second, providing real-time updates and clearing the interval once the countdown reaches zero, perfect for interactive user experiences.
4. Efficiently Sorting Object Arrays by Key
Understand how to sort an array of objects based on the values of a specific property. This generic function accepts an array and a property key, employing a standard comparison algorithm to arrange elements in ascending order, crucial for structured data presentation.
5. Eliminating Duplicate Entries from Arrays
Explore a simple yet powerful technique to create a new array containing only unique values from an existing array. This function leverages the Set
object, which inherently stores only unique values, to effectively filter out any repetitions, ensuring data integrity.
6. Concisely Truncating Long Strings
Discover how to shorten strings that exceed a specified length, appending an ellipsis (…) for readability. This utility intelligently checks the string’s length and, if necessary, trims it to the desired size before adding the visual indicator, ideal for UI displays.
7. Transforming Strings to Proper Title Case
Learn to convert any string into title case, where the first letter of each word is capitalized. This function employs regular expressions to identify word boundaries and applies a transformation to uppercase the initial character of every word, enhancing text presentation.
8. Checking for Element Presence in Arrays
Implement a straightforward function to determine if a particular value is present within an array. Utilizing the includes()
method, this utility offers an efficient way to check for element existence, returning a boolean result for quick conditional checks.
9. Reversing String Order Effortlessly
Explore how to easily reverse the characters of a string. This function breaks the string into an array of characters, reverses the order of elements, and then joins them back into a new string, a common task in string manipulation.
10. Incrementing Numeric Values in an Array
Discover a functional approach to create a new array where each number from the original array is incremented by one. This utility uses the map()
method, applying a simple arithmetic operation to each element without modifying the original array.
11. Implementing Function Debouncing for Performance
Understand the concept of debouncing and how to create a utility that delays function execution until after a specified pause in events. This pattern is crucial for performance optimization, preventing functions from being called too frequently during rapid user interactions like typing or resizing.
12. Throttling Function Calls for Controlled Execution
Learn about function throttling, a technique that limits how often a function can be called over a given period. This utility ensures that a function executes at most once within a defined time frame, vital for events like scrolling or mouse movement to maintain responsiveness without overwhelming the system.
13. Shallow Cloning JavaScript Objects
Explore a simple way to create a shallow copy of a JavaScript object. This function uses the spread syntax (...
) to copy enumerable own properties from a source object to a new object, useful when you need to modify an object without affecting the original.
14. Combining Multiple Objects into One
Discover how to efficiently merge the properties of two objects into a single new object. This utility leverages the spread syntax to combine properties, with later object properties overwriting earlier ones in case of key conflicts, offering a flexible way to compose data.
15. Identifying Palindrome Strings
Implement a function to check if a given string is a palindrome (reads the same forwards and backward), ignoring non-alphanumeric characters and case. This utility cleans the string, converts it to lowercase, and then compares it to its reversed counterpart.
16. Counting Element Frequencies in an Array
Learn to count the frequency of each unique element within an array, returning an object where keys are the elements and values are their counts. This function uses the reduce()
method to iterate and tally occurrences, providing valuable insights into data distribution.
17. Calculating the Day of the Year
Discover how to determine the numerical day of the year for any given date. This utility calculates the difference in milliseconds between the provided date and the start of its year, then converts it into the corresponding day count.
18. Extracting Unique Values from an Array
Explore a method to retrieve only the unique values from an array, similar to removing duplicates but focusing on the result. This function utilizes a Set
to automatically handle uniqueness and then converts the set back into an array.
19. Converting Angular Degrees to Radians
Learn the mathematical conversion from degrees to radians. This simple utility takes a degree value and applies the formula degrees * (Math.PI / 180)
to return the equivalent radian measure, essential for trigonometric calculations.
20. Deferring Function Execution Asynchronously
Understand how to schedule a function to be executed asynchronously after a minimal delay, effectively pushing it to the end of the current event loop. This defer
utility uses setTimeout
with a delay of 1 millisecond, useful for ensuring that certain operations run after the current call stack clears.
21. Capitalizing the Initial Letter of a String
Discover a straightforward function to capitalize only the first letter of a string while keeping the rest of the string as is. This utility extracts the first character, uppercases it, and concatenates it with the remainder of the string.
22. Chunking Arrays into Smaller Sub-Arrays
Learn to divide an array into smaller, equally sized chunks. This function takes an array and a chunk size, then returns an array of arrays, where each inner array contains elements up to the specified size, useful for pagination or batch processing.
23. Flattening Deeply Nested Arrays
Explore a convenient method to flatten a multi-dimensional array into a single-level array. This utility utilizes the flat()
method with Infinity
as its argument to recursively flatten all nested arrays, simplifying complex data structures.
24. Selecting a Random Element from an Array
Discover how to randomly pick an element from an array. This function generates a random index within the array’s bounds and returns the element at that position, useful for games, quizzes, or random data selection.
25. Randomly Shuffling Array Elements
Learn to randomize the order of elements within an array. This utility employs the sort()
method with a random comparison function, effectively shuffling the array in place, useful for creating randomness in lists or presentations.
26. Identifying the Maximum Value in a Number Array
Implement a simple function to find the largest number within an array of numbers. This utility uses Math.max()
combined with the spread operator to efficiently determine the maximum value among all elements.
27. Discovering the Minimum Value in a Number Array
Discover a concise way to find the smallest number within an array of numbers. Similar to finding the maximum, this function leverages Math.min()
with the spread operator to quickly identify the minimum value.
28. Filtering Out Null and Undefined Values
Learn to create a new array that excludes null
and undefined
values from an original array. This utility employs the filter()
method with a type guard to refine the array, ensuring data cleanliness and preventing potential errors.
29. Formatting Dates to YYYY-MM-DD Standard
Explore how to format a JavaScript Date
object into a standardized “YYYY-MM-DD” string format. This function utilizes toISOString()
to get an ISO date string and then extracts the date part, ideal for consistent date representation.
30. Rounding Numbers to Specific Decimal Places
Discover a precise method to round a number to a specified number of decimal places. This utility uses toFixed()
to format the number as a string and then parseFloat()
to convert it back to a number, ensuring accurate rounding.
31. Generating Unique Universal Identifiers (UUIDs)
Learn to generate a universally unique identifier (UUID) string conforming to the standard format. This function uses a pattern replacement with random hexadecimal digits to produce a unique 128-bit identifier, essential for distributed systems and unique key generation.
32. Determining if a Number is Even
Implement a basic function to check if a given number is even. This utility uses the modulo operator (%
) to determine if the number has a remainder of 0 when divided by 2, returning a boolean result.
33. Determining if a Number is Odd
Discover a simple way to check if a given number is odd. This function also employs the modulo operator, returning true
if the number has a non-zero remainder when divided by 2.
34. Asynchronously Pausing Execution (Sleep/Delay)
Learn to create an asynchronous “sleep” function that delays the execution of subsequent code for a specified number of milliseconds. This utility returns a Promise that resolves after the setTimeout
duration, enabling controlled pauses in async operations.
35. Implementing Robust Function Retries
Explore how to create a retry mechanism for an asynchronous function that might fail. This utility attempts to execute the function a specified number of times, catching errors and retrying until successful or the maximum retry limit is reached, improving fault tolerance.
36. Extracting Query Parameters from URLs
Discover how to parse a URL and extract its query parameters into a JavaScript object. This utility leverages the URL
and URLSearchParams
APIs to efficiently retrieve key-value pairs from the URL’s query string.
37. Generating Random Boolean Values
Implement a simple function to generate a random boolean value (true
or false
). This utility uses Math.random()
and compares it to 0.5 to produce an equal probability of either outcome.
38. Converting Objects to URL Query Strings
Learn to transform a JavaScript object into a URL-encoded query string. This utility utilizes URLSearchParams
to serialize key-value pairs, making it easy to construct URL query strings for API requests or navigation.
39. Performing Deep Clones of Objects
Explore a common technique for creating a deep copy of an object, meaning all nested objects and arrays are also copied, not just referenced. This utility uses JSON.parse(JSON.stringify(obj))
for a quick deep clone, suitable for plain data objects.
40. Compacting Arrays by Removing Falsey Values
Discover how to filter out all falsey values (e.g., false
, null
, 0
, ""
, undefined
, NaN
) from an array. This utility uses the filter()
method with the Boolean
constructor as a callback, creating a “compact” array of truthy values.
41. Validating if a String is Valid JSON
Implement a function to safely check if a given string is a valid JSON format. This utility attempts to parse the string using JSON.parse()
within a try-catch
block, returning true
if successful and false
if a parsing error occurs.
42. Generating Random Hexadecimal Color Codes
Learn to generate a random hexadecimal color code (e.g., “#RRGGBB”). This utility combines Math.random()
with bitwise operations and toString(16)
to produce a unique color string, useful for dynamic styling or visualizations.
43. Formatting Bytes into Human-Readable Sizes
Explore how to convert a byte count into a more human-readable format (e.g., “1.23 KB”, “4.56 MB”). This utility calculates the appropriate unit (Bytes, KB, MB, GB, TB) and formats the number to two decimal places, making file sizes easily understandable.
44. Detecting Substring Presence in a String
Implement a straightforward function to determine if a string contains a specific substring. This utility directly uses the includes()
method, providing a simple and efficient way to check for substring existence.
45. Extracting Specific Property Values from Object Arrays
Discover how to “pluck” or extract the values of a particular property from an array of objects. This utility uses the map()
method to iterate over the array and return a new array containing only the values for the specified key.
46. Finding the Intersection of Two Arrays
Learn to compute the intersection of two arrays, resulting in a new array containing only the elements common to both input arrays. This utility filters one array, keeping only the elements that are also present in the second array.
47. Calculating the Difference Between Two Arrays
Explore how to find the difference between two arrays, returning elements present in the first array but not in the second. This utility filters the first array, excluding any elements found in the second array.
48. Zipping Two Arrays into Pairs
Implement a function to “zip” two arrays together, creating an array of pairs where each pair contains corresponding elements from the input arrays. This utility uses map()
to combine elements based on their index.
49. Unzipping an Array of Pairs into Separate Arrays
Discover how to “unzip” an array of [key, value] pairs back into two separate arrays, one for keys and one for values. This utility employs the reduce()
method to deconstruct the pairs and build two distinct arrays.
50. Filtering Unique Objects by a Specific Property
Learn to filter an array of objects to keep only unique objects based on the value of a designated property. This utility uses a Set
to track seen property values, ensuring that only the first occurrence of an object with a given property value is retained.
Conclusion
These 50 TypeScript utility functions represent a powerful toolkit for any developer. By incorporating these well-crafted and commonly needed functionalities into your projects, you can write cleaner, more efficient, and more maintainable code. Embrace these utilities to elevate your TypeScript development practices and build robust applications with greater ease.