TypeScript One Liners
preetham
Posted on December 15, 2022
Wait
const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
await wait(1000); // waiting 1 second
Check id day is a weekday
const isWeekday = (d: Date): boolean => d.getDay() % 6 !== 0;
isWeekday(new Date(2022, 2, 21)); // -> true
isWeekday(new Date(2021, 2, 20)); // -> false
Reversing a string
const reverse = (s: string): string =>
s.split('').reverse().join('');
reverse('Hello'); // -> olleH
Check if the given number isEven
const isEven = (n: number): boolean => n % 2 === 0;
isEven(2); // -> true
isEven(3); // -> false
Capitalize given string
const capitalize = (s: string): string =>
s.charAt(0).toUpperCase() + s.slice(1);
capitalize('movie director'); // -> Movie Director
Check if an array is empty.
const isArrayEmpty = (arr: unknown[]): boolean =>
Array.isArray(arr) && !arr.length;
isArrayEmpty([]); // -> true
isArrayEmpty([1, 2, 3]); // -> false
Check if an object/array is empty.
const isObjectEmpty = (obj: unknown): boolean => obj &&
Object.keys(obj).length === 0;
isObjectEmpty({}); // -> true
isObjectEmpty({ foo: 'bar' }); // -> false
Generating a random integer.
const randomInteger = (min: number, max: number): number =>
Math.floor(Math.random() * (max - min + 1)) + min;
randomInteger(1, 10); // -> 7
💖 💪 🙅 🚩
preetham
Posted on December 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How I Created Vanilla Calendar Pro — A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024