Skip to content

Instantly share code, notes, and snippets.

@protzi
Last active June 9, 2022 09:44
Show Gist options
  • Select an option

  • Save protzi/fe2204508941ef302cd64fc844e49bc9 to your computer and use it in GitHub Desktop.

Select an option

Save protzi/fe2204508941ef302cd64fc844e49bc9 to your computer and use it in GitHub Desktop.
common functions
const isNil = val => val == null
const isString = val => typeof val === 'string' || val.constructor === String
const isNumber = val => !isNaN(parseFloat(val)) && isFinite(val)
const isPlainObject = val => val && val.constructor.name === 'Object'
const isObject = val => val && Object.prototype.toString.call(val) === '[object Object]'
const isFunction = fn => typeof fn === 'function'
const isClass = fn => isFunction(fn) && /^\s*class\s+/.test(fn.toString())
const isPromise = fn => fn.then && isFunction(fn.then)
const sleep = ms => new Promise(resolve => setTimeout(() => resolve(), ms))
const isEmptyArray = arr => Array.isArray(arr) && !arr.length
const isEmptyObject = obj => isObject(obj) && !Object.keys(obj).length
const isEmptyString = str => str === ''
const isZero = num => num === 0
const mapProp = prop => obj => obj[prop]
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)
const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x)
const camelToSnake = str => str.replace(/[\w]([A-Z])/g, (m) => m[0] + "_" + m[1] ).toLowerCase()
const toDateRange = (start, end) => {
const range = []
const dt = new Date(start)
while(dt <= end) {
range.push(new Date(dt))
dt.setDate(dt.getDate()+1)
}
return range
}
const paginateArray = (arr, page, limit) => arr.slice((page - 1) * limit, page * limit)
const deepCopy = (value) =>
Array.isArray(value)
? value.map((i) => deepCopy(i))
: isPlainObject(value) ? Object.entries(value).reduce((acc, [ k, v ]) => {
acc[k] = Array.isArray(v)
? v.map((i) => (isPlainObject(i) || Array.isArray(i)) ? deepCopy(i) : i)
: v
return acc;
}, {})
: value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment