1. ๐ฒ Generate a Random Number
function getRandomNumber(max: number): number {
return Math.floor(Math.random() * max);
}
2. ๐ฆ Check If an Object Is Empty
function isEmptyObject(obj: Record<string, unknown>): boolean {
return Object.keys(obj).length === 0;
}
3. โฑ๏ธ Create a Countdown Timer
function countdownTimer(minutes: number): void {
let seconds = minutes * 60;
const interval = setInterval(() => {
console.log(`${Math.floor(seconds / 60)}:${seconds % 60}`);
if (--seconds < 0) clearInterval(interval);
}, 1000);
}
4. ๐ Sort Array of Objects by Property
function sortByProperty<T>(arr: T[], prop: keyof T): T[] {
return arr.sort((a, b) => (a[prop] > b[prop] ? 1 : -1));
}
5. ๐งน Remove Duplicates from an Array
function removeDuplicates<T>(arr: T[]): T[] {
return [...new Set(arr)];
}
6. โ๏ธ Truncate a String
function truncateString(str: string, length: number): string {
return str.length > length ? `${str.slice(0, length)}...` : str;
}
7. ๐ Convert String to Title Case
function toTitleCase(str: string): string {
return str.replace(/\b\w/g, char => char.toUpperCase());
}
8. ๐ Check if Value Exists in Array
function valueExists<T>(arr: T[], value: T): boolean {
return arr.includes(value);
}
9. ๐ Reverse a String
function reverseString(str: string): string {
return str.split('').reverse().join('');
}
10. โ Create a New Array from Another
function incrementArray(arr: number[]): number[] {
return arr.map(num => num + 1);
}
11. ๐ง Debounce a Function
function debounce<F extends (...args: any[]) => void>(func: F, delay: number): F {
let timeout: ReturnType<typeof setTimeout>;
return function(this: any, ...args: any[]) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
} as F;
}
12. โก Throttle a Function
function throttle<F extends (...args: any[]) => void>(func: F, limit: number): F {
let lastRun = 0;
return function(this: any, ...args: any[]) {
const now = Date.now();
if (now - lastRun >= limit) {
func.apply(this, args);
lastRun = now;
}
} as F;
}
13. ๐งฌ Clone an Object
function cloneObject<T>(obj: T): T {
return { ...obj };
}
14. ๐ Merge Two Objects
function mergeObjects<T, U>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
15. ๐ Check for Palindrome String
function isPalindrome(str: string): boolean {
const cleaned = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return cleaned === cleaned.split('').reverse().join('');
}
16. ๐ข Count Occurrences in an Array
function countOccurrences<T>(arr: T[]): Record<string, number> {
return arr.reduce((acc, val) => {
const key = String(val);
acc[key] = (acc[key] || 0) + 1;
return acc;
}, {} as Record<string, number>);
}
17. ๐
Get Day of the Year
function getDayOfYear(date: Date): number {
const start = new Date(date.getFullYear(), 0, 0);
const diff = date.getTime() - start.getTime();
return Math.floor(diff / (1000 * 60 * 60 * 24));
}
18. ๐ Filter Unique Values from Array
function getUniqueValues<T>(arr: T[]): T[] {
return [...new Set(arr)];
}
19. ๐ Convert Degrees to Radians
function degreesToRadians(degrees: number): number {
return (degrees * Math.PI) / 180;
}
20. โณ Delay Function Execution
function defer(fn: (...args: any[]) => void, ...args: any[]): void {
setTimeout(() => fn(...args), 1);
}
Top comments (0)