/*
 * String utility functions
 * */

// 连字符转驼峰
const hyphenToHump = () => {
  return this.replace(/-(\w)/g, (...args) => {
    return args[1].toUpperCase();
  });
};

// 驼峰转连字符
const humpToHyphen = () => {
  return this.replace(/([A-Z])/g, '-$1').toLowerCase();
};

/**
 * @param   {String} name
 * @return  {String}
 */
const queryURL = (name: string) => {

  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
  const r = window.location.search.substr(1).match(reg);
  if (r !== null) { return decodeURI(r[2]); }
  return null;
};

/**
 * Convert object to query string
 * @param   {Object} obj
 * @return  {String}
 */
const JSON2QueryString = (obj) => {
  const str = [];
  for (const p in obj) {
    if (obj.hasOwnProperty(p) && obj[p]) {
      str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
    }
  }
  return str.join('&');
};

export default {
  JSON2QueryString,
  hyphenToHump,
  humpToHyphen,
  queryURL,
};
