Skip to content

Instantly share code, notes, and snippets.

@mallendeo
Last active February 5, 2021 20:26
Show Gist options
  • Save mallendeo/fadbad64eecbbf688e83910b41400d4e to your computer and use it in GitHub Desktop.
Save mallendeo/fadbad64eecbbf688e83910b41400d4e to your computer and use it in GitHub Desktop.
Simple helper functions
import * as crypto from 'crypto'
import iconv from 'iconv'
import ms from 'ms'
export const waitFor = (ms = 500): Promise<void> => new Promise((r) => setTimeout(r, ms))
export const cleanText = (text: string): string => text.trim().replace(/[\r\n\t®]/gi, '')
export const cleanPrice = (price: string): number => parseInt(price.replace(/[\$\.]/g, ''))
export const toSeconds = (time: string | number): number =>
typeof time === 'number' ? time : ms(time) / 1000
export const sha256 = (str: string): string => crypto.createHash('sha256').update(str).digest('hex')
export const encBase64 = (str: string): string => Buffer.from(str).toString('base64')
export const decBase64 = (str: string): string => Buffer.from(str, 'base64').toString('utf-8')
export const jsonToBase64 = (obj: any): string => encBase64(JSON.stringify(obj))
export const base64ToJSON = (str: string): string => JSON.parse(decBase64(str))
export const randomNum = (min: number, max: number, int = true): number => {
const range = [int ? Math.ceil(min) : min, int ? Math.floor(max) : max]
const rndNum = Math.random() * (range[1] - range[0] + 1)
return (int ? Math.floor(rndNum) : rndNum) + range[0]
}
export const createNumArr = (length: number, start = 0): number[] =>
Object.keys(Array(length).fill(1)).map((_, num) => +num + start)
export const convertToUTF8 = <T extends any>(body: T, fromEncoding = 'iso-8859-1'): T => {
const ic = new iconv.Iconv(fromEncoding, 'utf-8')
const buf = ic.convert(JSON.stringify(body))
return JSON.parse(buf.toString('utf-8'))
}
/**
* Get leafs / last items of a initial object with undefined number
* of children elements with a common array object key
*
* @param obj
* @param navKey
*
* @example
* const obj = {
* items: [
* { id: 1, items: [{ id: 10, items: false }] },
* { id: 2, items: [{ id: 11, items: [{ id: 12 }] }] },
* { id: 3, items: [{ id: 13 }] },
* ]
* }
*
* getLeafsByKey(obj, 'items')
* // [{ id: 10, items: false }, { id: 12 }, { id: 13 }]
*/
export const getLeafsByKey = (obj: unknown, navKey: string): Record<string, any>[] => {
const lastArr = []
const next = (item) => {
const curr = item[navKey]
if (!curr || !curr.length) return item
curr.forEach((childItem) => {
if (childItem[navKey] && childItem[navKey].length) {
next(childItem)
} else {
lastArr.push(childItem)
}
})
}
next(obj)
return lastArr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment