Below are some useful code snippets I wrote. I use them as a reference, because they when I occasionally need them, I never know them by heart. Hope this will help you too. If so, let me know in the comments.
Convert enum to array
export function enumToArray<T>(enumObj: object): T[] { const enumKeys: string[] = Object.keys(enumObj); const enumValues = enumKeys.map((key) => key as any).map((v) => enumObj[v] as any); return enumValues as T[]; }
Set all controls in Angular dynamic form to readonly
export function setFormReadonly(form: FormGroup, isReadonly: boolean) { Object.keys(form.controls).forEach((key) => { const control = form.controls[key]; if (isReadonly) { control.disable(); } else { control.enable(); } }); }
Get unique values of array
Works for array of primitive values only
export function getUniqueValues<T>(arr: T[]): T[] { return Array.from(new Set(arr)); }
Strip HTML tags from string
export function stripHtmlTags(html: string, options?: { preserveWhitespace: boolean }): string { if (!html) { return html; } let startWhitespace = ''; let endWhitespace = ''; if (options?.preserveWhitespace) { const startWhitespaceResult = /^\s/.exec(html); const endWhitespaceResult = /\s$/.exec(html); startWhitespace = startWhitespaceResult ? startWhitespaceResult[0] : ''; endWhitespace = endWhitespaceResult ? endWhitespaceResult[0] : ''; } const doc = new DOMParser().parseFromString(html, 'text/html'); return `${startWhitespace}${doc.body.textContent}${endWhitespace}` || ''; }
Replace all occurences of given string
export function replaceAll(str: string, find: string, replace: string) { return str.replace(new RegExp(find, 'g'), replace); }
Is empty object
export function isEmptyObject(obj: Object): boolean { return !obj || (Object.keys(obj).length === 0 && obj.constructor === Object); }
Is same day
export const isSameDay = (dateA: Date, dateB: Date): boolean => { const dayA = new Date(dateA.getFullYear(), dateA.getMonth(), dateA.getDate()); const dayB = new Date(dateB.getFullYear(), dateB.getMonth(), dateB.getDate()); return dayA.getTime() === dayB.getTime(); };