Last active
May 9, 2022 15:21
-
-
Save miguelsmuller/44ce933dc15bfbd2f1468ade8b9027c4 to your computer and use it in GitHub Desktop.
Quick Functions in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// WAIT | |
const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms)); | |
//await wait(1000); // waiting 1 second | |
// IS WEEKDAY | |
const isWeekday = (d: Date): boolean => d.getDay() % 6 !== 0; | |
//isWeekday(new Date(2022, 2, 21)); // -> true | |
//isWeekday(new Date(2021, 2, 20)); // -> false | |
//REVERSE | |
const reverse = (s: string): string => s.split('').reverse().join(''); | |
//reverse('elon musk'); // -> 'ksum nole' | |
// IS EVEN | |
const isEven = (n: number): boolean => n % 2 === 0; | |
//isEven(2); // -> true | |
//isEven(3); // -> false | |
// CAPITALIZE | |
const capitalize = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1); | |
//capitalize('lorem ipsum'); // -> Lorem ipsum | |
// IS ARRAY EMPTY | |
const isArrayEmpty = (arr: unknown[]): boolean => Array.isArray(arr) && !arr.length; | |
// isArrayEmpty([]); // -> true | |
// isArrayEmpty([1, 2, 3]); // -> false | |
// IS OBJECT EMPTY | |
const isObjectEmpty = (obj: unknown): boolean => obj && Object.keys(obj).length === 0; | |
// isObjectEmpty({}); // -> true | |
//isObjectEmpty({ foo: 'bar' }); // -> false | |
// RANDOM INTEGER | |
const randomInteger = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min; | |
//randomInteger(1, 10); // -> 7 | |
// RANDOM BOOLEAN | |
const randomBoolean = (): boolean => Math.random() >= 0.5; | |
// randomBoolean(); // -> true | |
// TOGGLE BOOLEAN | |
const toggleBoolean = (val: boolean): boolean => (val = !val); | |
//toggleBoolean(true); // -> false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment