From b5d6ee2afb8cf5430549e27f286652b78671d655 Mon Sep 17 00:00:00 2001 From: Isabella Hochschild <40366749+isabellahoch@users.noreply.github.com> Date: Wed, 18 Dec 2024 11:26:06 -0800 Subject: [PATCH] Create randomUtils.ts --- src/randomUtils.ts | 94 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/randomUtils.ts diff --git a/src/randomUtils.ts b/src/randomUtils.ts new file mode 100644 index 0000000..3a96e53 --- /dev/null +++ b/src/randomUtils.ts @@ -0,0 +1,94 @@ +/** + * Generates a random string of specified length + * @param length The desired length of the random string + * @returns A random string containing alphanumeric characters + */ +export function generateRandomString(length: number): string { + const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + + for (let i = 0; i < length; i++) { + const randomIndex = Math.floor(Math.random() * characters.length); + result += characters.charAt(randomIndex); + } + + return result; +} + +/** + * Chunks an array into smaller arrays of specified size + * @param array The input array to be chunked + * @param size The size of each chunk + * @returns An array of chunked arrays + */ +export function chunkArray(array: T[], size: number): T[][] { + const chunks: T[][] = []; + + for (let i = 0; i < array.length; i += size) { + chunks.push(array.slice(i, i + size)); + } + + return chunks; +} + +/** + * Debounces a function call + * @param func The function to debounce + * @param delay The delay in milliseconds + * @returns A debounced version of the function + */ +export function debounce any>( + func: T, + delay: number +): (...args: Parameters) => void { + let timeoutId: NodeJS.Timeout; + + return (...args: Parameters) => { + clearTimeout(timeoutId); + timeoutId = setTimeout(() => func(...args), delay); + }; +} + +/** + * Deep clones an object + * @param obj The object to clone + * @returns A deep clone of the input object + */ +export function deepClone(obj: T): T { + if (obj === null || typeof obj !== 'object') { + return obj; + } + + if (Array.isArray(obj)) { + return obj.map(item => deepClone(item)) as unknown as T; + } + + const clonedObj = {} as T; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + clonedObj[key] = deepClone(obj[key]); + } + } + + return clonedObj; +} + +/** + * Formats a number as a currency string + * @param amount The number to format + * @param currency The currency code (default: 'USD') + * @param locale The locale to use for formatting (default: 'en-US') + * @returns A formatted currency string + */ +export function formatCurrency( + amount: number, + currency: string = 'USD', + locale: string = 'en-US' +): string { + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: currency, + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }).format(amount); +}