export const ensureArray = (input: any) => (input ? (Array.isArray(input) ? input : [input]) : []) export const delay = (t: number) => { return new Promise((resolve) => { setTimeout(() => { resolve() }, t) }) } export const joinPaths = (...paths: string[]) => { return paths.reduce((finalPath, path, idx) => { if (idx === 0) { return path } if (path.startsWith('/')) { return path } if (finalPath.endsWith('/')) { return finalPath + path } return finalPath + '/' + path }, '') } export const reverse = (arr: T[]) => { const copy = [...arr] return copy.reverse() } // http://flyingsky.github.io/2018/01/26/javascript-detect-chinese-japanese/ const REGEX_CHINESE = /[\u4e00-\u9fff]|[\u3400-\u4dbf]|[\u{20000}-\u{2a6df}]|[\u{2a700}-\u{2b73f}]|[\u{2b740}-\u{2b81f}]|[\u{2b820}-\u{2ceaf}]|[\uf900-\ufaff]|[\u3300-\u33ff]|[\ufe30-\ufe4f]|[\uf900-\ufaff]|[\u{2f800}-\u{2fa1f}]/u export const hasChineseChar = (str) => REGEX_CHINESE.test(str) export function isValidIP(str: string) { const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)' const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}$`) return regex.test(str) } // TODO .com.cn 这类域名会有问题 export const getRootDomain = (hostname: string) => isValidIP(hostname) ? hostname : hostname .split('.') .slice(-2) .join('.') // https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript export function isEmail(email: string) { const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return re.test(email) } export const isThenable = (obj: any) => { try { return typeof obj.then === 'function' } catch (error) { return false } } export * from './color' export * from './diff' export * from './object-id' export * from './paginate'