/**
 * 检查字符串是否为空白
 *
 * @param str 待测字符串
 */
function isBlank(str?: string | null) {
  return str == null || str.trim().length === 0
}

/**
 * 检查字符串是否为空字符
 *
 * @param str 待测字符串
 */
function isEmpty(str?: string | null) {
  return str == null || str === ''
}

/**
 * 首字母大写
 *
 * @param str 待处理字符串
 */
function capitalize(str?: string | null) {
  if (isBlank(str)) return ''
  return str!.charAt(0).toUpperCase() + str!.slice(1)
}

let splitCharPattern = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g

/**
 * 以大写字母为分割符，转换成其他分隔符
 *
 * @param str 待处理字符串
 * @param joiner 连接符处理函数 (当前单词, 单词索引)=>单词处理后的结果
 */
function processWords(str: string | null | undefined, joiner: (word: string, index: number) => string) {
  if (isBlank(str)) return ''

  return (str!
    .replace(/([A-Z])/g, '$1')
    .toLowerCase()
    .match(splitCharPattern) as string[])
    .reduce((result, word, index) => result + joiner(word, index), '')
}

/**
 * 小驼峰
 *
 * @param str 待处理字符串
 */
function camelCase(str?: string) {
  return processWords(str,
    (word, index) => index !== 0 ? capitalize(word) : word,
  )
}

/**
 * 大驼峰
 *
 * @param str 待处理字符串
 */
function pascalCase(str?: string) {
  return capitalize(camelCase(str))
}

/**
 * 小写下滑线
 *
 * @param str 待处理字符串
 */
function snakeCase(str?: string) {
  return processWords(str,
    (word, index) => index !== 0 ? '_' + word : word,
  )
}

/**
 * 小写中横杠
 *
 * @param str 待处理字符串
 */
function kebabCase(str?: string) {
  return processWords(str,
    (word, index) => index !== 0 ? '-' + word : word,
  )
}

function isNumStr(str: any) {
  if (typeof str !== 'string') {
    return false
  }
  const reg = /^[+-]?\d+(\.\d+)?$/
  return reg.test(str)
}

export default {
  isBlank,
  isEmpty,
  capitalize,
  camelCase,
  snakeCase,
  kebabCase,
  pascalCase,
  processWords,
  isNumStr,
}
