preflower / blog

preflower's blog
0 stars 0 forks source link

工具方法汇总 #17

Open preflower opened 2 years ago

preflower commented 2 years ago

日期格式化

export function format(time, fmt = 'YYYY MM dd HH:mm:ss') {
  const date = new Date(time),
    o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours() % 12 || 12,
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length))
    }
  }
  return fmt
}
preflower commented 2 years ago

对象转字符串

/**
 * convert Object to match config's string
 * @param {Object} o provided Object
 * @param {Object} options provide filter, sort, eq, sep config
 * @returns match config's string
 */
export function stringify(o, options = {}) {
  if (!o) return o
  const {
    filter = false, // Filter value is [null, '', undefined]'s key
    sort = false, // Sort or not
    eq = '=', // Connector between key-value pairs
    sep = '&' // Separator between key-value pairs
  } = options

  const ret = []
  let keys = Object.keys(o)
  if (sort) {
    keys = keys.sort()
  }
  keys.forEach(key => {
    if (o[key] === '' || o[key] === null || o[key] === undefined) {
      if (!filter) ret.push(key)
    } else {
      ret.push(`${key}${eq}${o[key]}`)
    }
  })
  return ret.join(sep)
}
preflower commented 2 years ago

URL Query Parse with specify

/**
 * 返回url中指定key的value
 * @param {string} url 页面Url
 * @param {string} name 指定key
 */
export const getQueryVariable = (url, name = 'sn') => {
  url = unescape(url)
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  const r = url
    .substring(url.indexOf('?'))
    .substr(1)
    .match(reg)
  if (r != null) return unescape(r[2].replace(/\s+/g, ''))
  return null
}
preflower commented 2 years ago

URL Query Parse

/**
 * query 字符串解析器
 * @param url 需要被解析的query字符串
 * @returns {Object} 解析后的值,以键值对的形式
 */
export function querystring (url: string) {
  const parser = /([^=?#&]+)=?([^&]*)/g
  const query = url.substring(url.indexOf('?'))
  const result: {[k: string]: string} = {}
  let part

  while ((part = parser.exec(query)) != null) {
    const key = decode(part[1])
    const value = decode(part[2])

    if (key === null || value === null || key in result) continue
    result[key] = value
  }

  return result
}

/**
 * 解码 URI 字符串
 * @param {String} input 译码后的字符串
 * @returns 解码后的字符串
 */
function decode (input: string) {
  try {
    return decodeURIComponent(input.replace(/\+/g, ' '))
  } catch (e) {
    return null
  }
}
preflower commented 2 years ago

timeout Promise化

/**
 * Promise的形式封装 sleep 函数
 * @param delay 延迟时间
 * @returns 
 */
export function sleep (delay: number = 0): Promise<void> {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(undefined)
        }, delay)
    })
}