
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
A list of utility functions that can be used in a variety of typescript and javascript projects.
This is a collection easy utility functions I found myself copying and pasting over various personal and work projects. I am not going to gate-keep the code, that will be provided in this README as well if you just want to have them in your code base without installing the entire project. Having this project makes things easier for me, but I am not going to pretend like every project on the planet is going to need a "capitalizeFirstLetters" function.
Using npm:
npm install ez-funcs
Using yarn:
yarn add ez-funcs
Using bun:
bun install ez-funcs
Using pnpm:
pnpm add ez-funcs
Using bower:
bower install ez-funcs
Once the package is installed, you can import the library using import
approach:
import { tryCatch } from 'ez-funcs';
This functions takes a string and returns the same string with the first letters of each word capitalized.
import { capitalizeFirstLetters } from 'ez-funcs';
const text = 'hello world';
const newText = capitalizeFirstLetters(text);
console.log(newText); // Output: Hello World
export function capitalizeFirstLetters(str: string | null) {
if (!str) return '';
return str
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
This function takes a number or a string representing a number and returns formatted dollar amount as a string. It supports different currencies and handles invalid inputs gracefully.
import { createDollarAmount } from 'ez-funcs';
const amountString = '200';
const newAmountOne = createDollarAmount(amountString);
console.log(newAmountOne); // Output: $200.00
const amountNumber = 200;
const newAmountTwo = createDollarAmount(amountNumber);
console.log(newAmountTwo); // Output: $200.00
export function createDollarAmount(
amountInput: number | string,
currency: SupportedCurrency = 'USD'
): string {
if (amountInput === null || amountInput === undefined || amountInput === '') {
const defaultAmount = 0; // Default amount if input is null, undefined, or empty string
return defaultAmount.toLocaleString(CURRENCY_LOCALE_MAP[currency], {
style: 'currency',
currency: currency
});
}
const numericAmount = Number(amountInput);
// 1. Handle invalid numeric input
if (isNaN(numericAmount)) {
// You can decide how to handle this:
// - Throw an error (often preferred for library functions)
// - Return a specific string like "Invalid Amount" or an empty string
// - Return a default formatted value like $0.00
// For this example, let's throw an error.
throw new TypeError(
"Invalid 'amountInput': failed to convert to a number."
);
}
// 2. Get the locale from the map
// This replaces the large switch statement.
const locale = CURRENCY_LOCALE_MAP[currency];
// 3. Use a try-catch block for the toLocaleString call
// This can catch errors if the locale or options are somehow invalid,
// though with the current setup, it's less likely for supported currencies.
try {
return numericAmount.toLocaleString(locale, {
style: 'currency',
currency: currency // The 'currency' option takes the ISO currency code
});
} catch (error) {
console.error(
`Error formatting currency ${currency} for locale ${locale}:`,
error
);
// Fallback behavior: re-throw, or return a specific error string,
// or even a basic formatting if possible.
// For now, let's return an error message string.
return `Error formatting ${currency}`; // Or throw the error
}
}
This function extracts a number from a string, removing all non-numeric characters except for commas and decimal points. It returns the number as a float or null if the number cannot be parsed.
import { extractNumber } from 'ez-funcs';
const inputString = '2,812.30 refund minus 25% CANCELLATION FEE.';
const result = extractNumber(inputString);
console.log(result); // Output: 2812.3
export function extractNumber(input: number | string) {
input = input.toString();
// Remove all characters except digits, commas, and decimal points
const cleaned = input.replace(/[^0-9.,]/g, '');
// Remove commas
const normalized = cleaned.replace(/,/g, '');
// Parse as float
const number = parseFloat(normalized);
return isNaN(number) ? null : number;
}
This function formats a phone number string into a standard format of
(123) 456-7890. It supports both 10-digit and 11-digit numbers, where the
latter starts with a '1'.
import { formatPhone } from 'ez-funcs';
const phoneNumber = '1234567890';
const formattedPhone = formatPhone(phoneNumber);
console.log(formattedPhone); // Output: (123) 456-7890
export function formatPhone(phoneNumber: string) {
const cleaned = ('' + phoneNumber).replace(/\D/g, '');
// Check for 10-digit number
let match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
// If no match, check for 11-digit number starting with 1
if (!match && cleaned.length === 11 && cleaned.charAt(0) === '1') {
match = cleaned.match(/^1(\d{3})(\d{3})(\d{4})$/);
}
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`;
}
return null;
}
This function takes an object and returns a new object with all string properties trimmed of leading and trailing whitespace. Non-string properties are left unchanged.
import { trimStringProperties } from 'ez-funcs';
const userInput = {
name: ' John Doe ',
email: ' john@example.com ',
age: 30,
isActive: true
};
const cleanedInput = trimStringProperties(userInput);
console.log(cleanedInput);
// Output: { name: 'John Doe', email: 'john@example.com', age: 30, isActive: true }
export function trimStringProperties<T extends Record<string, unknown>>(obj: T): T {
const result = {} as T;
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const value = obj[key];
if (typeof value === 'string') {
result[key as keyof T] = value.trim() as T[keyof T];
} else {
result[key as keyof T] = value as T[keyof T];
}
}
}
return result;
}
This function truncates a string to a specified length and appends an ellipsis (...) if the string exceeds that length. It also ensures that the string does not end with a space before the ellipsis.
import { truncateText } from 'ez-funcs';
const text 'Imagine this is super long text that needs to be truncated';
const truncatedText = truncateText(text, 20);
console.log(truncatedText); // Output: Imagine this is super long...
export function truncateText(text: string, length: number) {
if (text.length <= length) {
return text;
}
return text.slice(0, length) + '...';
}
This function executes a given function and catches any errors that occur in a much more elegant way than the built in try-catch functionality. It returns an object with the result or error. This functions exists in every project I create and I highly recommend using it. However, if you have came up with a better solution please send it my way! Also, I am not going to try to take credit for this one this comes from Theo, if you don't watch his YouTube videos maybe give them a shot! https://www.youtube.com/@t3dotgg.
import { tryCatch } from 'ez-funcs';
async function something() {
const { data, error } = await tryCatch(async () => {
const response = await fetch('/api/some-endpoint');
return response.json();
});
if (error) {
console.error('Error fetching data:', error);
} else {
console.log('Fetched data:', data);
}
}
// Types for the result object with discriminated union
type Success<T> = {
data: T;
error: null;
};
type Failure<E> = {
data: null;
error: E;
};
type Result<T, E = Error> = Success<T> | Failure<E>;
// Main wrapper function
export async function tryCatch<T, E = Error>(
promise: Promise<T>
): Promise<Result<T, E>> {
try {
const data = await promise;
return { data, error: null };
} catch (error) {
return { data: null, error: error as E };
}
}
If you have any suggestions visit the contact me page on my website! -> Contact Me
FAQs
A list of utility functions that can be used in a variety of typescript and javascript projects.
We found that ez-funcs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.