developer-plus / interview

https://interview.developer-plus.org
MIT License
9 stars 1 forks source link

写个函数, 可以转化下划线命名到驼峰命名 #24

Open Hongbusi opened 2 years ago

Hongbusi commented 2 years ago
function underlineToHump(str) {
  return str.replace(/\_(\w)/g, (_, letter) => {
    return letter.toUpperCase()
  })
}
TickHeart commented 2 years ago
function toHump(str: string): string {
  return str.replace(/\_(\w)/g, (_, letter) => {
    return letter.toUpperCase();
  })
}
myltx commented 2 years ago
function toHump(str) {
  return str
    .replace(/[_]/g, '/')
    .split('/')
    .reduce((previous, current) => previous + current.replace(/^\w/, (s) => s.toUpperCase()), '');
}
ChenHaoJie9527 commented 2 years ago

组合函数实现

const compose = (...args: any[]) => values => args.reverse().reduce((prev, current)=> current(prev), values);
const strReplace = (str: string) => str.replace(/[_]/g, '');
const strToUpperCase = (str: string) => str.replace(/w/g, (strs, letter) => {
  return strs.toUpperCase();
})

const flowRight = compose(strToUpperCase, strReplace);
console.log('flowRight: ', flowRight('hello_world'));
lyx-jay commented 2 years ago

中规中矩的实现

function trans(str:string):string {
  if (!str.includes('_')) return str;
  let flag:boolean = false;
  let res:string = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] !== '_') {
      res += (flag && i !== 1) ? str[i].toUpperCase() : str[i]
      flag = false;
    } else {
      flag = true;
    }
  }
  return res;
}