Last active
July 27, 2020 10:45
-
-
Save pdashford/23b7fc17be662ce648dbbbf585e7af3d to your computer and use it in GitHub Desktop.
Some of my helper routines commonly used within my Angular projects
This file contains 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
import { Observable } from 'rxjs' | |
import moment from 'moment' | |
export const isEmpty = (obj) => { | |
return !obj || Object.keys(obj).length === 0 | |
} | |
export const isObservable = (obj: any) => { | |
return obj instanceof Observable | |
} | |
export const decodeString = (str: string): string => Buffer.from(str, 'base64').toString('binary') | |
export const encodeString = (str: string): string => Buffer.from(str, 'binary').toString('base64') | |
export function pick<T extends object, U extends keyof T>(obj: T, paths: Array<U>) { | |
return paths.reduce((o, k) => { | |
o[k] = obj[k] | |
return o | |
}, Object.create(null)) | |
} | |
export const groupBy = (items, key) => | |
items.reduce( | |
(result, item) => ({ | |
...result, | |
[item[key]]: [...(result[item[key]] || []), item] | |
}), | |
{} | |
) | |
export const flattenArrays = (arr) => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flattenArrays(b) : b), []) | |
export function groupArrayBy(list, keyGetter) { | |
const map = new Map() | |
list.forEach((item) => { | |
const key = keyGetter(item) | |
const collection = map.get(key) | |
if (!collection) { | |
map.set(key, [item]) | |
} else { | |
collection.push(item) | |
} | |
}) | |
return map | |
} | |
export function addDays(d: Date, days: number): Date { | |
return moment(d).utc().add(days, 'day').toDate() | |
} | |
export function getMonthDiff(start: Date, end: Date) { | |
return moment(start).diff(moment(end), 'month', false) | |
} | |
export const uniqueBy = (prop) => (list) => { | |
const uniques = {} | |
return list.reduce((result, item) => { | |
if (uniques[item[prop]]) return result | |
uniques[item[prop]] = item | |
return [...result, item] | |
}, []) | |
} | |
export const toCurrency = (n, digits = 2) => { | |
return new Intl.NumberFormat('en-GB', { | |
minimumFractionDigits: digits, | |
style: 'currency', | |
currency: 'GBP' | |
}).format(n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment