codewars--js--Convert all the cases!
问题描述:
In this kata, you will make a function that converts between camelCase, snake_case, and kebab-case.
You must write a function that changes to a given case. It must be able to handle all three case types:
js> changeCase("snakeCase", "snake")
"snake_case"
js> changeCase("some-lisp-name", "camel")
"someLispName"
js> changeCase("map_to_all", "kebab")
"map-to-all"
js> changeCase("doHTMLRequest", "kebab")
"do-h-t-m-l-request"
js> changeCase("invalid-inPut_bad", "kebab")
undefined
js> changeCase("valid-input", "huh???")
undefined
js> changeCase("", "camel")
""
我的思路:
先将不符合要求的筛选出来,return undefined;
然后通过swich(targetCase),分别转换。
我的答案:
通过为171 / 174。问题出现在部分不符合要求的不能识别。
function changeCase(identifier, targetCase){
// Your code here!
var a=["snake","camel","kebab"];
var id=identifier.split("");
if(identifier==""){return "";}
if(a.indexOf(targetCase)=="-1"|| (identifier.indexOf("-")!=-1 &&identifier.indexOf("_")!=-1 || (identifier.indexOf("-")!=-1 && identifier.indexOf(/A-Z/)!=-1) ||(identifier.indexOf(/A-Z/)!=-1 && identifier.indexOf("_")!=-1))){return undefined;}
switch(targetCase)
{
case "snake":
for(var i=0;i<id.length;i++){
if(/[A-Z]/.test(id[i])){
id.splice(i,0,"_",id[i+1].toLowerCase());
i++;
}
if(/[-]/.test(id[i])){
id.splice(i,1,'_')
}
}
return id.join("");
break;
case "camel":
for(var i=0;i<id.length;i++){
if(/-/.test(id[i]) || /_/.test(id[i])){
id.splice(i,2,id[i+1].toUpperCase());
//i=i-1;
}
}
return id.join("");
break;
case "kebab":
for(var i=0;i<id.length;i++){
if(/[A-Z]/.test(id[i])){
id.splice(i,0,"-");
i++;
}
if(/[-]/.test(id[i])){
id.splice(i,1,'-')
}
}
return id.join("");
break;
}
}
优秀答案:
(1)
function changeCase(identifier, targetCase){
if(!/^$|^[a-z]+(([A-Z][a-z]*)+|(-[a-z]+)*|(_[a-z]+)*)$/.test(identifier)) return undefined;
switch(targetCase){
case 'snake': return identifier.replace(/-([a-z])|([A-Z])/g, (_,x,y) => '_'+(x||y.toLowerCase()));
case 'camel': return identifier.replace(/[-_]([a-z])/g, (_,x) => x.toUpperCase());
case 'kebab': return identifier.replace(/_([a-z])|([A-Z])/g, (_,x,y) => '-'+(x||y.toLowerCase()));
default: return undefined;
}
}
(2)
function changeCase(i, t){
if ( ( /[A-Z]/.test(i) + /[_]/.test(i) + /[-]/.test(i)) > 1 ) //这个好理解,当[A-Z],-,_,三者任意两个出现的时候,返回undefined
return undefined;
else if (t == "snake" )
return i.replace(/[A-Z]/g,a=>'_'+a.toLowerCase()).replace(/-([a-z])/g,(_,a)=> '_'+a);//先大写转“_”+小写,然后将所有-x转成_+小写
else if ( t== 'camel')
return i.replace(/_/g,'-').replace(/-([a-z])/g,(_,a)=> a.toUpperCase()); //先_转-,然后将-后面的第一个字母大写
else if (t== 'kebab' )
return i.replace(/_/g,'-').replace(/[A-Z]/g,a=>'-'+a.toLowerCase());//先_转-,然后将大写字母小写
}
(3)建议这个,方便好懂,前面两个正则略复杂,不易懂
将所有单词分开,放入到数组中。
当需要用的时候,按照snake/kebab/camel的格式连接。
function changeCase(identifier, targetCase){
if (identifier === '') {
return '';
}
if (/^[a-z-]+$/.test(identifier)) {
identifier = identifier.split('-');
}
else if (/^[a-z_]+$/.test(identifier)) {
identifier = identifier.split('_');
}
else if (/^[a-z][A-Za-z]+$/.test(identifier)) {
identifier = identifier.replace(/([A-Z])/g, ' $1').toLowerCase().split(' '); //在大写字母前加空格,然后全部转小写,然后按空格分割
}
else {
return undefined;
}
switch (targetCase) {
case 'snake' : identifier = identifier.join('_'); break;
case 'kebab' : identifier = identifier.join('-'); break;
case 'camel' : identifier = identifier.map( (x,i) => i === 0 ? x : x[0].toUpperCase() + x.slice(1)).join(''); break;
default : return undefined
}
return identifier;
}
哈哈哈!
codewars--js--Convert all the cases!的更多相关文章
- moment.js & convert timestamps to date string in js
moment.js & convert timestamps to date string in js https://momentjs.com/ moment().format('YYYY- ...
- [CodeWars][JS]实现链式加法
在知乎上看到这样一个问题:http://www.zhihu.com/question/31805304; 简单地说就是实现这样一个add函数: add(x1)(x2)(x3)...(xn) == x1 ...
- [CodeWars][JS]实现大整数加法
问题描述 实现‘字符串加法’,即将两个以字符串形式表示的数字相加,得到结果然后返回一个新的字符串. 例如:输入‘123’,‘321’,返回‘444’. 这样在进行两个任意大的整数相加的时候,既不会溢出 ...
- [CodeWars][JS]如何判断给定的数字是否整数
问题描述: We are asking for a function to take a positive integer value, and return a list of all positi ...
- JS模块化库seajs体验
seajs http://seajs.org/docs/en.html#intro https://github.com/seajs/seajs/releases Extremely simple e ...
- 读《Ext.JS.4.First.Look》随笔
Ext JS 4是最大的改革已经取得了Ext框架.这些变化包括一个新类系统,引入一个新的平台,许多API变化和改进,和新组件,如新图表和新画组件.Ext JS 4是更快,更稳定,易于使用.(注意:Ex ...
- 【翻译】将Ext JS Grid转换为Excel表格
原文:Converting an Ext 5 Grid to Excel Spreadsheet 稍微迟来的礼物--Ext JS Grid转为Excel代码,现在支持Ext JS 5! 功能包括: - ...
- 【深度学习】K-L 散度,JS散度,Wasserstein距离
度量两个分布之间的差异 (一)K-L 散度 K-L 散度在信息系统中称为相对熵,可以用来量化两种概率分布 P 和 Q 之间的差异,它是非对称性的度量.在概率学和统计学上,我们经常会使用一种更简单的.近 ...
- Hacker's guide to Neural Networks
Hacker's guide to Neural Networks Hi there, I'm a CS PhD student at Stanford. I've worked on Deep Le ...
- dwr入门
dwr2.0的jar包,还需要同时导入log4j.jar和commons-loggin.jar 首先是配置文件: <!-- DWR配置 --> <servlet> <se ...
随机推荐
- 造轮子-toast组件的实现(下)
1.解决 toast 中传入 html 的问题,通过假的 slot 来实现 // plugins.js toast.$slots.default = [message] // toast.vue &l ...
- Mysql一分钟定位 Next-Key Lock,你需要几分钟
连接与线程 查看连接信息 show processlist +----+------+------------------+------+---------+------+----------+--- ...
- Go的切片:长度和容量
虽然说 Go 的语法在很大程度上和 PHP 很像,但 PHP 中却是没有"切片"这个概念的,在学习的过程中也遇到了一些困惑,遂做此笔记. 困惑1:使用 append 函数为切片追加 ...
- JPA_映射关联关系
一:单项多对一的关联关系 例如:订单和客户 1.新创建订单类 package com.atguigu.jpa.helloworld; import javax.persistence.Column; ...
- a标签跳转小程序
随着小程序应用的逐步广泛,与公众号之前的协同运营越来越重要,通过公众号的各个入口为小程序导流.最近在运营中发现,大家对公众号关注后回复.关键词回复,超链接小程序的需求. 首先把小程序绑定 ...
- Leetcode 题目整理
1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a ...
- springcloud 依赖版本问题
SpringCloud 版本: 版本名称 版本 Finchley snapshot版 Edgware snapshot版 Dalston SR1 当前最新稳定版本 Camden SR7 稳定版本 Br ...
- 编译出适合自己的nginx
上面是解压后的nginx源码 auto目录 上面的cc目录用于编译,lib库 os目录对系统进行判断,其他所有文件都是辅助conf脚本执行 判定nginx支持哪些模块,当前操作系统有哪些特性. CHA ...
- 关于PreparedStatement.addBatch()方法
Statement和PreparedStatement的区别就不多废话了,直接说PreparedStatement最重要的addbatch()结构的使用. 1.建立链接,(打电话拨号 ) Connec ...
- Sophus库CMakeLists.txt内容详解笔记
CMakeLists.txt: SET(PROJECT_NAME Sophus) PROJECT(${PROJECT_NAME}) CMAKE_MINIMUM_REQUIRED(VERSION 2.6 ...