DEV Community

preetham
preetham

Posted on

TypeScript One Liners

Wait

const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
Enter fullscreen mode Exit fullscreen mode

await wait(1000); // waiting 1 second

Check id day is a weekday

const isWeekday = (d: Date): boolean => d.getDay() % 6 !== 0;
Enter fullscreen mode Exit fullscreen mode

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('');
Enter fullscreen mode Exit fullscreen mode

reverse('Hello'); // -> olleH

Check if the given number isEven

const isEven = (n: number): boolean => n % 2 === 0;
Enter fullscreen mode Exit fullscreen mode

isEven(2); // -> true
isEven(3); // -> false

Capitalize given string

const capitalize = (s: string): string => 
    s.charAt(0).toUpperCase() + s.slice(1);
Enter fullscreen mode Exit fullscreen mode

capitalize('movie director'); // -> Movie Director

Check if an array is empty.

const isArrayEmpty = (arr: unknown[]): boolean => 
    Array.isArray(arr) && !arr.length;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

randomInteger(1, 10); // -> 7

Top comments (0)