常用工具函数
集合
export const sortArr = (length, start = 1) => new Array(length).fill(null).map((_,index) => index + start)
export const randomArr = (length, start = 1) => sortArr(length, start).sort(() => Math.random() - 0.5)
export const remove = (arr, el) => {
const i = arr.indexOf(el)
if (i > -1) {
arr.splice(i, 1)
}
}
export const valueEquals = (a, b) => {
if (a === b) return true
if (!(a instanceof Array)) return false
if (!(b instanceof Array)) return false
if (a.length !== b.length) return false
for (let i = 0; i !== a.length; ++i) {
if (a[i] !== b[i]) return false
}
return true
}
export const hasOwn = (val, key ) => Object.prototype.hasOwnProperty.call(val, key)
export const deepCopy = (obj) => {
var ret = {}, key, val
for (key in obj) {
if (hasOwn(obj, key)) {
val = obj[key];
if (isObject(isObject)) {
ret[key] = deepCopy(val)
} else {
ret[key] = val
}
}
}
return ret
}
export const debounce = (func, await=300, immediate = true) {
let timer;
const debounced = function(){
const ctx = this;
const args = arguments;
if(timer) clearTimeout(timer);
if(immediate){
let callNow = !timer;
timer = setTimeout(()=>{
timer = null;
}, await)
if(callNow) return func.apply(ctx,args);
}else {
timer = setTimeout(function(){
func.apply(ctx,args);
}, await);
}
}
debounced.cancel = function(){
if(timer) clearTimeout(timer);
timer = null;
}
return debounced;
}
1、初始化有序数组
export const sortArr = (length, start = 1) => new Array(length).fill(null).map((_,index) => index + start)
2、获取乱序数组
export const randomArr = (length, start = 1) => sortArr(length, start).sort(() => Math.random() - 0.5)
3、移除数组中的项
export const remove = (arr, el) => {
const i = arr.indexOf(el)
if (i > -1) {
arr.splice(i, 1)
}
}
4、判断两数组中的值是否相等
export const valueEquals = (a, b) => {
if (a === b) return true
if (!(a instanceof Array)) return false
if (!(b instanceof Array)) return false
if (a.length !== b.length) return false
for (let i = 0; i !== a.length; ++i) {
if (a[i] !== b[i]) return false
}
return true
};
5、深克隆对象
export const hasOwn = (val, key ) => Object.prototype.hasOwnProperty.call(val, key)
export const deepCopy = (obj) => {
var ret = {}, key, val
for (key in obj) {
if (hasOwn(obj, key)) {
val = obj[key]
if (isObject(isObject)) {
ret[key] = deepCopy(val)
} else {
ret[key] = val
}
}
}
return ret
}
6、防抖
export const debounce = (func, await=300, immediate = true) {
let timer;
const debounced = function(){
const ctx = this;
const args = arguments;
if(timer) clearTimeout(timer);
if(immediate){
let callNow = !timer;
timer = setTimeout(()=>{
timer = null;
}, await)
if(callNow) return func.apply(ctx,args);
}else {
timer = setTimeout(function(){
func.apply(ctx,args);
}, await);
}
}
debounced.cancel = function(){
if(timer) clearTimeout(timer);
timer = null;
}
return debounced;
}