1.0.6 • Published 3 years ago
gongyongfunction v1.0.6
/**
* 常规函数
*/
/**
* 判断数据是否为指定的数据类型,如果是则返回true。
* @param {*} type 源对象类型
* @param {*} val 目标对象
*/
export const is = (type, val) => ![, null].includes(val) && val.constructor === type;
console.log(is(Array,[]))
console.log(is(Object,{}))
console.log(is(String,''))
...
/**
* 是否为null
* @param {*} val
*/
export const isNull = val => val === null;
/**
* 是否数值类型
* @param {*} val
*/
export const isNumber = val => !isNaN(parseFloat(val)) && isFinite(val);
/**
* 是否数组类型
* @param {*} obj
*/
export const isArray = obj => Array.isArray(obj);
/**
* 是否正整数
* @param {*} val
*/
export const isPositiveNum = val => /^[1-9]\d*$/.test(val);
/**
* 是否负整数
* @param {*}} val
*/
export const isNegativeNum = val => /^-[1-9]\d*$/.test(val);
/**
* 匹配整数
* @param {*} val
*/
export const isInteger = val => /^(-|\+)?\d+$/.test(val);
/**
* 匹配正浮点数
*/
export const isPostiveFloat = val => /^[1-9]\d*.\d*|0.\d*[1-9]\d*$/.test(val)
/**
* 匹配负浮点数
*/
export const isNegativeFloat = val => /^-([1-9]\d*.\d*|0.\d*[1-9]\d*)$/.test(val)
/**
* 匹配浮点数
*/
export const isFloat = val => /^-?([1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0)$/.test(val)
/**
* 用于判断程序运行环境是否在浏览器。
*/
export const isBrowser = () => ![typeof window, typeof document].includes('undefined');
/**
* 是否质数
* @param {*} num
*/
export const isPrime = num => (num > 1) && Array(Math.floor(Math.sqrt(num)) - 1).fill(0).map((_, i) => i + 2).every(i => num % i !== 0);
/**
* 检查字符串是否包含空格
* @param {*} str
*/
export const isHasWhitespace = str => /\s/.test(str);
/**
* 检查字符串是否为十六进制颜色
* @param {*} color
*/
export const isHexColor = color => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);
/**
* 检查字符串是否为十六进制数字
* @param {*} str
*/
export const isHexadecimal = str => /^[A-F0-9]+$/i.test(str);
/**
* 检查值是否为字符串
* @param {*} value
*/
export const isString = value => Object.prototype.toString.call(value) === '[object String]';
/**
* 是否对象
* @param {*} v
*/
export const isObject = v => (v !== null && typeof v === 'object');
/**
* 是否是函数
* @param {*} v
*/
export const isFunction = v => ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(Object.prototype.toString.call(v));
/**
* 验证中文姓名
* @param {string} value
*/
export const isChineseName = value => /^(?:[\u4e00-\u9fa5·]{2,16})$/g.test(value);
/**
* 验证英文姓名
*@param { string } value
*/
export const isEnglishName = value => /(^[a-zA-Z]{1}[a-zA-Z\s]{0,20}[a-zA-Z]{1}$)/g.test(value);
/**
* 是否手机号码
* @param {*} val
*/
export const isPhone = (val) => /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(val);
/**
* 是否邮箱
* @param {*} val
*/
export const isEmail = (val) => /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(val);
/**
* 是否emoji字符
*/
export const isEmoji = (val) => /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\ufe0f|\u200d|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/g.test(val);
/**
* 是否强密码,至少6位,包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符
* @param {*} val
*/
export const isPwdStrength = val => /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/.test(val);
/**
* 是否URL地址
* @param {*} val
*/
export const isUrl = val => /^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/.test(val);
/**
* 节流
* 节流操作使回调函数在每隔一段时间定期执行一次,时间间隔内再触发,不会重新执行。
* @param {*} func
* @param {*} timerNumber
*/
export const throttle = (func, wait = 100) => {
let timer = null;
return (...args) => {
if (timer) {
return;
}
timer = setTimeout(() => {
func(...args)
timer = null;
}, wait)
}
}
/**
* 防抖
* 短时间内多次触发一个函数,只执行最后一次,或在开始时执行
* @param {*} fn
* @param {*} delay
*/
export const debounce = (fn, delay=200) => {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, delay);
}
}
/**
* 深度克隆对象
* @param {*} obj
*/
export const deepClone = (obj, hash = new WeakMap()) => {
if (obj instanceof RegExp) return new RegExp(obj)
if (obj instanceof Date) return new Date(obj)
if (obj === null || typeof obj !== 'object') {
return obj
}
if (hash.has(obj)) {
return hash.get(obj)
}
let t = new obj.constructor()
hash.set(obj, t)
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
t[key] = deepClone(obj[key], hash)
}
}
return t
}
/**
* 回到顶部,针对window整个页面的
*/
export const goToTop = (isAnimation = false) => {
//直接到顶部
if (isAnimation) {
window.scrollTo(0, 0);
return true;
}
//滚动到顶部
scrollToTop();
return true;
}
//滚动到顶部
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
/**
* 某个具备class元素内置滚动轴回到顶部,只处理第一个
*/
export const goToTopClassName = (className) => {
let el = document.getElementsByClassName(className);
if (!el[0]) {
throw (`未能找到class为 ${className} 的节点,请确认`)
}
el[0].scrollTo(0, 0);
};
/**
* 某个具备id元素内置滚动轴回到顶部
*/
export const goToTopId = (id, isAnimation = false) => {
let el = document.getElementById(id);
if (!el) {
throw (`未能找到id为 ${ID} 的节点,请确认`)
}
if (isAnimation) {
el.scrollIntoView({
behavior: 'smooth'
})
return;
}
if (el.scrollIntoView) {
el.scrollIntoView();
} else if (el.scrollIntoViewIfNeeded) {
el.scrollIntoViewIfNeeded();
}
};
/**
* 获取所选元素
*/
export const getSelectedText = () => window.getSelection().toString();
/**
* 存储到localStorage
* 说明:对象值如果是函数 、RegExp等特殊对象存贮会被忽略
* @param { String } key 属性
* @param { string } value 值
*/
export const setLocalStorage = (key, value) => {
if (typeof (value) === 'object') value = JSON.stringify(value);
localStorage.setItem(key, value)
return true;
};
/**
* 读取localStorage存储值
* @param {String} key 属性
*/
export const getLocalStorage = (key) => localStorage.getItem(key);
/**
* 删除localStorage存储值
* @param {String} key 属性
*/
export const delLocalStorage = (key) => localStorage.removeItem(key);
/**
* 增加sessionStorage值
* @param {*} key
* @param {*} value
*/
export const setSessionStorage = (key, value) => sessionStorage.setItem(key, value);
/**
* 读取sessionStorage值
* @param {*} key
*/
export const getSessionStorage = (key) => sessionStorage.getItem(key);
/**
* 删除sessionStorage值
* @param {*} key
*/
export const delSessionStorage = (key) => sessionStorage.removeItem(key);
/**
* 创建cookie
* @param {*} key
* @param {*} value
* @param {*} expireHours 过期时间 默认24小时
*/
export const setCookie = (key, value, expireHours = 24) => {
let path = "/";
let date = Date.now() + expireHours * 60 * 60 * 1000; // cookie过期时间
date = new Date(date).toUTCString();
document.cookie = key + "=" + encodeURIComponent(value) + ((!expireHours) ? "" : ("; expires=" + date)) + ";path=" + path + ";";
return true;
}
/**
* 获取cookie
* @param {*} key
*/
export const getCookie = (key) => {
let reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
let arr = document.cookie.match(reg);
return arr ? arr[2] : null;
}
/**
* 删除cookie
* @param {*} key
*/
export const delCookie = (key) => getCookie(key) ? setCookie(key, "", -1) : false;
/**
* 获取页面可视高度
*/
export const pageViewHeight = () => {
let d = document,
a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
return a.clientHeight;
}
/**
* 获取页面可视宽度
*/
export const pageViewWidth = () => {
let d = document,
a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
return a.clientWidth;
}
/**
* 获取滚动轴位置
* @param {*} el
*/
export const scrollPostion = (el = window) =>
({
x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop
});
/**
* 复制文本
* @param {*} str
*/
export const copyText = (str) => {
const el = document.createElement("textarea");
el.value = str;
el.setAttribute("readonly", "");
el.style.position = "absolute";
el.style.left = "-9999px";
el.style.top = "-9999px";
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) :
false;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
return true;
}
/**
* 进入全屏
* @param {*} selector
*/
export const fullScreen = (selector = document.body) => {
if (selector.requestFullscreen) {
selector.requestFullscreen();
} else if (selector.mozRequestFullScreen) {
selector.mozRequestFullScreen();
} else if (selector.webkitRequestFullscreen) {
selector.webkitRequestFullscreen();
} else if (selector.msRequestFullscreen) {
selector.msRequestFullscreen();
}
//return true;
};
/**
* 退出全屏
*/
export const exitFullscreen = () => {
if (document.exitFullScreen) {
document.exitFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
//return true;
}
/**
* 是否全屏状态
*/
export const isFullScreen = () => {
return !!(
document.mozFullScreen ||
document.webkitIsFullScreen ||
document.webkitFullScreen ||
document.msFullScreen
);
}
/**
* 随机16进制颜色
*/
export const randomHexColor = () => '#' + (Math.random() * 0xfffff * 1000000).toString(16).slice(0, 6);
/**
* 随机生成布尔值
*/
export const randomBoolean = () => Math.random() >= 0.5;
/**
* 随机生成浮点数据
* @param {*} min
* @param {*} max
*/
export const randomFloat = (min = 0, max = 1) => Math.random() * (max - min) + min;
/**
* 首字母大写
* @param {*} param0
*/
export const capitalize = ([first, ...rest]) => first.toUpperCase() + rest.join('');
/**
* 每个首字母都大写
* @param {*} str
*/
export const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
/**
* 首字母小写
* @param {*} param0
*/
export const decapitalize = ([first, ...rest]) => first.toLowerCase() + rest.join('')
/**
* 每个首字母都小写
* @param {*} str
*/
export const decapitalizeEveryWord = str => str.replace(/\b[A-Z]/g, char => char.toLowerCase());
/**
* 是否为空
* @param {*} any
*/
function typeOfString(obj) {
const type = typeof obj;
// 由于 typeof null 输出 'object',这里特殊处理 null
if (obj === null) {
return 'null';
} else if (type === 'object') {
// 统一处理,主要是 Array 及类型 Array;Set;Map;等
return Object.prototype.toString.call(obj);
} else {
return type;
}
}
export const isEmpty = (obj) => {
let _isEmpty = false;
const type = typeOfString(obj);
// 对数组和对象做判断
if (type === '[object Object]') {
if (Object.keys) {
const keys = Object.keys(obj);
_isEmpty = keys.length <= 0;
} else {
_isEmpty = JSON.stringify(obj) === '{}'
}
} else if (type === '[object Array]') {
_isEmpty = obj.length <= 0;
} else {
_isEmpty = !Boolean(obj);
}
return _isEmpty;
}
function fileRead(a) {
const reader = new FileReader();
let file=a.slice(0,100)
reader.readAsArrayBuffer(file);
return new Promise((resolve, reject) => {
reader.onload = (event) => {
try {
let array = new Uint8Array(event.target.result);
array = array.slice(0, 4);
let arr = [...array]
let key = arr.map(item => item.toString(16)
.toUpperCase()
.padStart(2, '0'))
.join('')
resolve(key)
} catch (e) {
reject(e);
}
};
});
}
## ========返回值是Promise======================================
/**
* 是否是jpg
* @param {*} any
*/
export const isJpg = async file => {
const ms = 'FFD8FFE0';
const data = await fileRead(file)
return ms == data
}
/**
* 是否是png
* @param {*} any
*/
export const isPng = async file => {
const ms = '89504E47';
const data = await fileRead(file)
return ms == data
}
/**
* 是否是gif
* @param {*} any
*/
export const isGif = async file => {
const ms = '47494638';
const data = await fileRead(file)
return ms == data
}
/**
* 是否是Pdf
* @param {*} any
*/
export const isPdf = async file => {
const ms = '25504446';
const data = await fileRead(file)
return ms == data
}
/**
* 是否是mp4
* @param {*} any
*/
export const isMp4 = async file => {
const ms = '00000020';
const data = await fileRead(file)
return ms == data
}