Skip to content

Instantly share code, notes, and snippets.

@web-crab
Last active November 15, 2019 16:16
Show Gist options
  • Save web-crab/7c3c590afaa44af86bb12a5385abc50e to your computer and use it in GitHub Desktop.
Save web-crab/7c3c590afaa44af86bb12a5385abc50e to your computer and use it in GitHub Desktop.
export const URL_PATTERNS = [
{ prefix: 'tel', re: /(\+7)[\s\-()0-9]{10,}/ },
{ prefix: 'mailto', re: /^.+@.+$/ }
]
/**
* @param {Promise[]} promises
* @returns Promise
*/
export function promiseQueue (promises = []) {
return promises.reduce((promise, _) => promise.then(_), Promise.resolve())
}
/**
* @param {any} val
* @returns {any}
*/
export function deepClone (val) {
return JSON.parse(JSON.stringify(val))
}
/**
* @returns {boolean}
*/
export function isMobile () {
const regExp = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
return regExp.test(navigator.userAgent)
}
/**
* @param {Date} d1
* @param {Date} d2
* @param {string} unit - minutes || hours || days
* @returns {number}
*/
export function dateDiff (d1, d2, unit = 'days') {
d1 = new Date(d1)
d2 = new Date(d2)
const ms = {
'minutes': 60000,
'hours': 3600000,
'days': 86400000
}[unit]
if (!ms) {
throw new Error(`dateDiff: Third argument must be an minutes/hours/days`)
}
return Math.round((d2 - d1) / ms)
}
/**
* capitalize('abc') // 'Abc'
* @param {string} str
* @returns {string}
*/
export function capitalize (str) {
if (!str || typeof str !== 'string') {
throw new Error(`capitalize: Invalid argument "${str}"`)
}
return str[0].toUpperCase() + str.substr(1)
}
/**
* @param {Object} context - class context
*/
export function bindAllMethods (context) {
Object.getOwnPropertyNames(context.__proto__)
.forEach((method) => context[method] = context[method].bind(context))
}
/**
* @returns {boolean} - is mobile device
*/
export function isMobile() {
return navigator
? /Android|iPhone|iPad|iPod|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
: false
}
/**
* shortenNumber(1500000) // '1.5 млн'
* @param {number} n
* @returns {string}
*/
export const shortenNumber = (n) {
if (n < 1e3) return n.toString()
if (n < 1e6) return `${n / 1e3} тыс`
if (n < 1e9) return `${n / 1e6} млн`
return `${n / 1e9} млрд`
}
/**
* formateAmount(1500000) // '1 500 000,00 руб.'
* @param {number} n
* @returns {string}
*/
const formateAmount = (n) => {
return `${n.toFixed(2).toString().replace('.', ',').replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ')} руб.`
}
/**
* deepFindChild([{ children: [{ id: 1 }] }], 'id', 1) // { id: 1 }
* @param {Object[]} children
* @param {string} key
*/
const deepFindChild = (children, key, val) => {
for (let child of children) {
if (child[key] === val) {
return child
} else if (child.children) {
child = utils.deepFindChild(child.children, key, val)
if (child) return child
}
}
return null
}
/**
* decline(1, ['штука', 'штуки', 'штук']) // '1 штука'
* decline(2, ['штука', 'штуки', 'штук']) // '2 штуки'
* decline(5, ['штука', 'штуки', 'штук']) // '5 штук'
* @param {number} n - кол-во
* @param {string[]} variations - формы слова для 1 2 5 шт
* @returns {string}
*/
const decline = (n, variations) => {
const word = variations[(n % 100 > 4 && n % 100 < 20) ? 2 : [2, 0, 1, 1, 1, 2][(n % 10 < 5) ? n % 10 : 5]]
return `${n} ${word}`
}
/**
* isLink('[email protected]') // true
* @param str
* @returns {boolean}
*/
const isLink = (str) => {
return !!URL_PATTERNS.find(({ re }) => re.test(str))
}
/**
* makeHref('[email protected]') // 'mailto:[email protected]'
* @param url
* @returns {string}
*/
const makeHref = (url) => {
const pattern = URL_PATTERNS.find((_) => _.re.test(url))
return pattern ? `${pattern.prefix}:${url}` : url
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment