codewars-js练习
2021/3/2
github 地址
【1】<7kyu>【Shifter words】
You probably know that some characters written on a piece of paper, after turning this sheet 180 degrees, can be read, although somitimes in a different way. So, uppercase letters “H”, “I”, “N”, “O”, “S”, “X”, “Z” after rotation are not changed, the letter “M” becomes a “W”, and Vice versa, the letter “W” becomes a “M”.
example:
shifter("SOS IN THE HOME") === 2 // shifter words are "SOS" and "IN"
shifter("WHO IS SHIFTER AND WHO IS NO") === 3 // shifter words are "WHO", "IS", "NO"
shifter("TASK") === 0 // no shifter words
shifter("") === 0 // no shifter words in empty string
solution
<script type="text/javascript">
function shifter(s){
// console.log(s);
if(s == '')return 0
// 去重数组
let arr = [...new Set(s.split(' '))];
// console.log(arr);
let num = 0;
for(let i=0;i<arr.length;i++){
if((/[HINOSXZMW]/g).test(arr[i])){
var temp = arr[i].match(/[HINOSXZMW]/g).join('');
if(temp == arr[i])num ++;
}
}
return num;
}
// 验证
console.log(shifter("ON"));// 1
console.log(shifter("WHO IS SHIFTER AND WHO IS NO"));//3
console.log(shifter(""));//0
console.log(shifter("I III A III"));//2
</script>
【2】<7kyu>【Separate basic types】
Given: a sequence of different type of values (number, string, boolean). You should return an object with a separate properties for each of types presented in input. Each property should contain an array of corresponding values.
- keep order of values like in input array
- if type is not presented in input, no corresponding property are expected
即分离number、string和boolean
example:
['a', 1, 2, false, 'b']//{number: [1, 2],string: ['a', 'b'],boolean: [false]}
['a', 1, 2 ]//{number: [1, 2], string: ['a']}
solution
<script type="text/javascript">
function separateTypes(input) {
// console.log(input)
let map = {};
let str = [];
let num = [];
let bool = [];
for(let i=0;i<input.length;i++){
if(typeof input[i] == 'string')str.push(input[i])
else if(typeof input[i] == 'number')num.push(input[i])
else if(typeof input[i] == 'boolean')bool.push(input[i])
}
if(str.length!=0)map['string'] = str;
if(num.length!=0)map['number'] = num;
if(bool.length!=0)map['boolean'] = bool
// console.log(map)
return map
}
// 验证
console.log(separateTypes(['a', 1, 2, false, 'b']));//{number: [1, 2],string: ['a', 'b'],boolean: [false]}
console.log(separateTypes(['a', 1, 2 ]));//{number: [1, 2], string: ['a']}
</script>
以上为自己思路供大家参考,可能有更优的思路。