Skip to content

Instantly share code, notes, and snippets.

@alsolovyev
Last active May 14, 2021 20:30
Show Gist options
  • Select an option

  • Save alsolovyev/eabb24d7ec9cb4040a1680b44baadfa4 to your computer and use it in GitHub Desktop.

Select an option

Save alsolovyev/eabb24d7ec9cb4040a1680b44baadfa4 to your computer and use it in GitHub Desktop.
Helpful JavaScript functions

Helpful JavaScript functions

copy- copy to clipboard
createElement - create the HTML element specified by tagName formatPhoneNumber - formats a string into a human-readable phone number getRandomBool - get a random boolean value
getRandomFloat - get a random floating point number between min and max
getRandomInt - get a random integer between min and max
isArray - checks if data is classified as an Array primitive
isNumber - checks if data is classified as a Number primitive
isString - checks if data is classified as a String primitive
lerp - get the linear interpolation between two value
memo - create a function that memorizes the result of the passed function

/**
* Performs selection from either `text` or `target`
* properties and then executes copy.
*
* @param {String|HTMLElement} target - a content to copy
*/
const copy = (() => {
const textarea = document.createElement('textarea')
textarea.style.position = 'absolute'
textarea.style.left = '-9999px'
textarea.style.top = `${window.pageYOffset || document.documentElement.scrollTop}px`
textarea.setAttribute('readonly', '')
return target => {
document.body.appendChild(textarea)
textarea.value = target && typeof target === 'object' && target.nodeType === 1 ? target.value || target.innerText : target
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
})()
/**
* Returns a HTML element
*
* @param {String} tag - Tag name
* @param {String} className - Class name
* @returns {HTMLElement} - HTML element
*/
const createElement = (tag, className) => {
const element = document.createElement(tag)
if (className)
className.split(/\s+/).forEach(name => element.classList.add(name))
return element
}
/**
* Creates a function to format a phone numbers.
*
* @param {Array} [codes=[380, 375, 8, 7]] - a list of available country calling codes
* @returns {Function}
*/
const createPhoneFormater = (codes = [380, 375, 8, 7]) => {
const countryCodes = codes.join('|')
const regExp = new RegExp(
`^(?<code>${countryCodes})(?<city>\\d{1,3})?(?<xxx>\\d{1,3})?(?<xx>\\d{1,2})?(?<yy>\\d{1,2})?`
)
// For IE support
// const regExp = new RegExp(`^(${countryCodes})(\\d{1,3})?(\\d{1,3})?(\\d{1,2})?(\\d{1,2})?`)
/**
* Formats a string into a human-readable phone number.
*
* @param {String} str - a string with numbers
* @returns {String} a formatted string.
*/
return str => {
const numbers = str.replace(/[^\d]+/g, '')
const matches = numbers.match(regExp)
let result = '+'
if (matches) {
const { code, city, xxx, xx, yy } = matches.groups
// For IE support
// const [, code, city, xxx, xx, yy] = matches
code && (result += `${code}`)
city && (result += ` (${city}`)
xxx && (result += `) ${xxx}`)
xx && (result += `-${xx}`)
yy && (result += `-${yy}`)
}
else {
result += numbers.slice(0, 11)
}
return result
}
}
/**
* Get a random boolean value.
*
* @return {boolean} a random true/false
*/
const getRandomBool = () => Math.random() >= 0.5
/**
* Get a random floating point number between `min` and `max`.
*
* @param {number} min - The min number
* @param {number} max - The max number
* @returns {number} a random floating point number
*/
const getRandomFloat = (min, max) => Math.random() * (max - min) + min
/**
* Get a random integer between `min` and `max`.
*
* @param {number} min - The min number
* @param {number} max - The max number
* @return {number} a random integer
*/
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
/**
* Checks if `data` is classified as an `Array` primitive.
*
* @param {*} data - The data to check
* @returns {boolean} `true` if `data` is an array, else `false`.
*/
const isArray = Array.isArray
/**
* Checks if `data` is classified as a `Number` primitive.
*
* @param {*} data - The data to check
* @returns {boolean} `true` if `data` is a number, else `false`.
*/
const isNumber = data => toString.call(data) === '[object Number]'
/**
* Checks if `data` is classified as a `String` primitive.
*
* @param {*} data - The data to check
* @returns {boolean} `true` if `data` is a string, else `false`.
*/
const isString = data => toString.call(data) === '[object String]'
/**
* Get the linear interpolation between two values.
*
* @param {number} v0 - The starting value
* @param {number} v1 - The destination value
* @param {number} t - The normal value (between 0 and 1) to control the linear interpolation
* @return {number} a value between two numbers at a specified, decimal midpoint
*/
const lerp = (v0, v1, t) => (1 - t) * v0 + t * v1
/**
* Creates a function that memorizes the result of the passed function.
*
* @param {function} fn - The pure function
* @return {function} a result of the pure function
*
* @example
* const fn = memo(fn)
*/
const memo = fn => {
const cache = Object.create(null)
return n => {
if (!cache[n]) cache[n] = fn(n)
return cache[n]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment