Skip to content

Instantly share code, notes, and snippets.

@pdashford
Last active July 27, 2020 10:45
Show Gist options
  • Save pdashford/23b7fc17be662ce648dbbbf585e7af3d to your computer and use it in GitHub Desktop.
Save pdashford/23b7fc17be662ce648dbbbf585e7af3d to your computer and use it in GitHub Desktop.
Some of my helper routines commonly used within my Angular projects
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