JS工具函数

博客 动态
0 189
优雅殿下
优雅殿下 2023-06-10 00:10:13
悬赏:0 积分 收藏

JS工具函数

工具函数

用于工程化开发,记录,备用

返回 [min, max) 间的随机整数

/** 返回 [min, max) 间的随机整数 */
export function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min) + min)
}

返回随机id

/**
 * 返回随机id
 * @returns {String}
 */
export function randomId() {
  const char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let result = ''
  for (let i = 0; i < 16; i++) {
    result += char[getRandom(0, char.length)]
  }
  return result
}

判断一个值是否是Object

/**
 * 判断一个值是否是Object
 * @param {*} value
 * @returns {Boolean}
 */
export function isObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]'
}

判断value是否为空

/**
 * 判断value是否为空
 * @param {*} value
 * @returns {Boolean}
 */
export function isEmpty(value) {
  if (value === null || typeof value === 'undefined') {
    return true
  }
  if (typeof value === 'number' && isNaN(value)) {
    return true
  }
  if (typeof value === 'string' && value === '') {
    return true
  }
  if (Array.isArray(value) && value.length <= 0) {
    return true
  }
  if (isObject(value) && Object.keys(value).length <= 0) {
    return true
  }
  return false
}

判断value是否不为空

/**
 * 判断value是否不为空
 * @param {*} value
 * @returns {Boolean}
 */
export function isNotEmpty(value) {
  return !isEmpty(value)
}

赋值对象属性

/**
 * 将origin中的属性赋值到target中
 * @param {Object} target 目标对象
 * @param {Object} origin 源对象
 * @returns {Object}
 */
export function copyProp(target, origin) {
  if (!isObject(target) || !isObject(origin)) {
    throw new Error('Argument must be of object type!')
  }
  if (isEmpty(origin)) {
    return target
  }
  for (const key in origin) {
    target[key] = origin[key]
  }
  return target
}

深拷贝

仅支持对象和数组

/** 深拷贝 */
export function deepClone(value) {
  if (typeof value !== 'object' || isEmpty(value)) {
    return value
  }
  let result = Array.isArray(value) ? [] : {}
  for (const key in value) {
    result[key] = deepClone(value[key])
  }
  return result
}

模拟异步延时

/**
 * 模拟异步延时
 * @param {Number} [duration=500] 延迟的时间(ms)
 * @returns {Promise}
 */
export function delay(duration = 500) {
  return new Promise((resolve) => setTimeout(resolve, duration))
}

函数只调用一次函数

/**
 * 函数只调用一次函数
 * @param {Function} fn
 * @returns {Function}
 */
export function once(fn) {
  let executed = false
  return () => {
    if (!executed) {
      executed = true
      fn.apply(this, ...arguments)
    }
  }
}

防抖

/**
 * 防抖
 * @param {Function} fn 要进行防抖的函数
 * @param {Number} [duration=100] 延迟时间
 * @returns {Function}
 */
export function debounce(fn, duration = 100) {
  let timer = null
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, duration)
  }
}

节流

/**
 * 节流
 * @param {Function} fn 要节流的函数
 * @param {Number} [duration=50] 延迟时间
 * @returns
 */
export function throttle(fn, duration = 50) {
  let mark = 0
  return () => {
    if (Date.now() - mark >= duration) {
      fn.apply(this, arguments)
      mark = Date.now()
    }
  }
}

返回顶部

/** 返回顶部 */
export function goTop() {
  window.scroll({
    top: 0,
    left: 0,
    behavior: 'smooth',
  })
}

获取url参数

/**
 * 获取url参数
 * @param {String} [url=location.href] url地址,不传使用当前网站url
 * @returns {Object}
 */
export function getUrlParams(url = location.href) {
  const index = url.indexOf('?')
  const result = {}
  if (index === -1) {
    return result
  }
  const arr = url.substring(index + 1).split('&')
  for (let i = 0; i < arr.length; i++) {
    const param = arr[i].split('=')
    result[param[0]] = param[1]
  }
  return result
}

完整文件

/** 返回 [min, max) 间的随机整数 */
export function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min) + min)
}

/**
 * 返回随机id
 * @returns {String}
 */
export function randomId() {
  const char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let result = ''
  for (let i = 0; i < 16; i++) {
    result += char[getRandom(0, char.length)]
  }
  return result
}

/**
 * 判断一个值是否是Object
 * @param {*} value
 * @returns {Boolean}
 */
export function isObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]'
}

/**
 * 判断value是否为空
 * @param {*} value
 * @returns {Boolean}
 */
export function isEmpty(value) {
  if (value === null || typeof value === 'undefined') {
    return true
  }
  if (typeof value === 'number' && isNaN(value)) {
    return true
  }
  if (typeof value === 'string' && value === '') {
    return true
  }
  if (Array.isArray(value) && value.length <= 0) {
    return true
  }
  if (isObject(value) && Object.keys(value).length <= 0) {
    return true
  }
  return false
}

/**
 * 判断value是否不为空
 * @param {*} value
 * @returns {Boolean}
 */
export function isNotEmpty(value) {
  return !isEmpty(value)
}

/**
 * 将origin中的属性赋值到target中
 * @param {Object} target 目标对象
 * @param {Object} origin 源对象
 * @returns {Object}
 */
export function copyProp(target, origin) {
  if (!isObject(target) || !isObject(origin)) {
    throw new Error('Argument must be of object type!')
  }
  if (isEmpty(origin)) {
    return target
  }
  for (const key in origin) {
    target[key] = origin[key]
  }
  return target
}

/** 深拷贝 */
export function deepClone(value) {
  if (typeof value !== 'object' || isEmpty(value)) {
    return value
  }
  let result = Array.isArray(value) ? [] : {}
  for (const key in value) {
    result[key] = deepClone(value[key])
  }
  return result
}

/**
 * 模拟异步延时
 * @param {Number} [duration=500] 延迟的时间(ms)
 * @returns {Promise}
 */
export function delay(duration = 500) {
  return new Promise((resolve) => setTimeout(resolve, duration))
}

/**
 * 函数只调用一次函数
 * @param {Function} fn
 * @returns {Function}
 */
export function once(fn) {
  let executed = false
  return () => {
    if (!executed) {
      executed = true
      fn.apply(this, ...arguments)
    }
  }
}

/**
 * 防抖
 * @param {Function} fn 要进行防抖的函数
 * @param {Number} [duration=100] 延迟时间
 * @returns {Function}
 */
export function debounce(fn, duration = 100) {
  let timer = null
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, duration)
  }
}

/**
 * 节流
 * @param {Function} fn 要节流的函数
 * @param {Number} [duration=50] 延迟时间
 * @returns
 */
export function throttle(fn, duration = 50) {
  let mark = 0
  return () => {
    if (Date.now() - mark >= duration) {
      fn.apply(this, arguments)
      mark = Date.now()
    }
  }
}

/** 返回顶部 */
export function goTop() {
  window.scroll({
    top: 0,
    left: 0,
    behavior: 'smooth',
  })
}

/**
 * 获取url参数
 * @param {String} [url=location.href] url地址,不传使用当前网站url
 * @returns {Object}
 */
export function getUrlParams(url = location.href) {
  const index = url.indexOf('?')
  const result = {}
  if (index === -1) {
    return result
  }
  const arr = url.substring(index + 1).split('&')
  for (let i = 0; i < arr.length; i++) {
    const param = arr[i].split('=')
    result[param[0]] = param[1]
  }
  return result
}

posted @ 2023-06-10 00:00  摇摆的鱼  阅读(0)  评论(0编辑  收藏  举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2012 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员