codewars-js练习
2021/2/4
github 地址
【1】<7kyu>【Sorted? yes? no? how?】
Complete the method which accepts an array of integers, and returns one of the following:
"yes, ascending"
- if the numbers in the array are sorted in an ascending order"yes, descending"
- if the numbers in the array are sorted in a descending order"no"
- otherwise
example:
it("[1, 2]", function() {
Test.assertEquals(isSortedAndHow([1, 2]), 'yes, ascending');
});
it("[15, 7, 3, -8]", function() {
Test.assertEquals(isSortedAndHow([15, 7, 3, -8]), 'yes, descending');
});
it("[4, 2, 30]", function() {
Test.assertEquals(isSortedAndHow([4, 2, 30]), 'no');
});
solution
<script type="text/javascript">
function isSortedAndHow(array) {
// console.log(array);
var array1 = JSON.parse(JSON.stringify(array));
var array2 = JSON.parse(JSON.stringify(array));
var array3 = JSON.parse(JSON.stringify(array));
// console.log('array深拷贝后',array1);
// 升序排序
var arr = array.sort((a,b)=>{return a-b});
// console.log('array升序排序后',arr);
// 降序排序
var arr1 = array3.sort((a,b)=>{return b-a});
// console.log('array降序排序后',arr1);
if(arr.toString() == array1.toString()){
return 'yes, ascending';
}else if(arr1.toString() == array2.toString()){
return 'yes, descending';
}else{
return 'no';
}
}
// 验证
console.log(isSortedAndHow([1,2])); // 'yes, ascending'
console.log(isSortedAndHow([15, 7, 3, -8])); // 'yes, descending'
console.log(isSortedAndHow([4, 2, 30]));//'no'
</script>
【2】<7kyu>【Sort Numbers】
Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
example:
solution([1, 2, 10, 50, 5]); // should return [1,2,5,10,50]
solution(null); // should return []
solution
<script type="text/javascript">
function solution(nums){
// console.log(nums);
return (nums || []).sort((a, b)=>{return a - b});
}
// 验证
console.log(solution([1,2,10,50,5])); // [1,2,5,10,50]
console.log(solution(null)); //[]
</script>
以上为自己思路供大家参考,可能有更优的思路。