/**
* Get cookie from request.
*
* @param {Object} req
* @param {String} key
* @return {String|undefined}
*/
export function cookieFromRequest (req, key) {
if (!req.headers.cookie) {
return
}
const cookie = req.headers.cookie.split(';').find(
c => c.trim().startsWith(`${key}=`)
)
if (cookie) {
return cookie.split('=')[1]
}
}
/**
* https://router.vuejs.org/en/advanced/scroll-behavior.html
*/
export function scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
let position = {}
if (to.matched.length < 2) {
position = { x: 0, y: 0 }
} else if (to.matched.some(r => r.components.default.options.scrollToTop)) {
position = { x: 0, y: 0 }
} if (to.hash) {
position = { selector: to.hash }
}
return position
}
/**
* Deep copy the given object.
*
* @param {Object} obj
* @return {Object}
*/
export function deepCopy (obj) {
if (obj === null || typeof obj !== 'object') {
return obj
}
const copy = Array.isArray(obj) ? [] : {}
Object.keys(obj).forEach((key) => {
copy[key] = deepCopy(obj[key])
})
return copy
}
/**
* If the given value is not an array, wrap it in one.
*
* @param {Any} value
* @return {Array}
*/
export function arrayWrap (value) {
return Array.isArray(value) ? value : [value]
}
export function passwordChecker () {
return {
strong: new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})'),
medium: new RegExp('^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})')
}
}
export function formatDateISO8601 (date) {
if (Object.prototype.toString.call(date) === '[object Date]') {
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
}
return null
}
export function formatDate (date) {
if (Object.prototype.toString.call(date) === '[object Date]') {
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear()
}
return null
}
export function localeArray2Assoc (arr, keyArg = 'value', valueArg = 'text') {
const ret = []
if (arr) {
for (const key in arr) {
ret.push({
[keyArg]: key,
[valueArg]: arr[key]
})
}
}
return ret
}
export function debounce (fn, time) {
let timeout
return function () {
const functionCall = () => fn.apply(this, arguments)
clearTimeout(timeout)
timeout = setTimeout(functionCall, time)
}
}
export function getAge (birthDate) {
const ageDifMs = Date.now() - new Date(birthDate).getTime()
const ageDate = new Date(ageDifMs) // milliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970)
}