signed

QiShunwang

“诚信为本、客户至上”

codewars练习(javascript)-2021/3/21

2021/3/21 9:04:50   来源:

文章目录

    • codewars-js练习
      • 2021/3/21
        • github 地址
        • 【1】<8kyu>【Will there be enough space?】
        • 【2】<7kyu>【Sum - Square Even, Root Odd】
        • 【3】<8kyu>【Returning Strings】

codewars-js练习

2021/3/21

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<8kyu>【Will there be enough space?】

He wants you to write a simple program telling him if he will be able to fit all the passengers.

example

enough(10, 5, 5);
// 0, He can fit all 5 passengers
enough(100, 60, 50);
// 10, He can't fit 10 out of 50 waiting

solution

<script type="text/javascript">
    function enough(cap, on, wait) {
        console.log(cap,on,wait)
        if(on + wait > cap)return Math.abs(cap - (on+wait));
        else return 0;
    }
    // 验证
    console.log(enough(10, 5, 5));// 0
    console.log(enough(100, 60, 50));// 10
    console.log(enough(20, 5, 5));// 0
</script>

【2】<7kyu>【Sum - Square Even, Root Odd】

取列表中的每一个数字,如果它是偶数,它的平方,或者如果它是奇数,它的平方根。获取这个新的列表并返回它的和,四舍五入到小数点后两位。

example

[4,5,7,8,1,2,3,0]//91.61
[1,14,9,8,17,21]//272.71

solution

<script type="text/javascript">
    const sumSquareEvenRootOdd = ns => {
        console.log(ns)
        var temp = [];
        for(var i=0;i<ns.length;i++){
            if(ns[i] % 2 == 0)temp.push(Math.pow(ns[i],2));
            else if(ns[i] % 2 !=0) temp.push(Math.sqrt(ns[i]));
        }
        return  parseFloat(sum(temp).toFixed(2));
    };
    
    function sum(arr) {
        return eval(arr.join("+"));
    };
    // 验证
    console.log(sumSquareEvenRootOdd([4,5,7,8,1,2,3,0]));//91.61
    console.log(sumSquareEvenRootOdd([1,14,9,8,17,21]));//272.71
</script>

【3】<8kyu>【Returning Strings】

example

"Ryan"// "Hello, Ryan how are you doing today?"

solution

<script type="text/javascript">
    function greet(name){
        return "Hello, " + name + " how are you doing today?"
    }
    // 验证
    console.log(greet("Ryan"));// "Hello, Ryan how are you doing today?"
    console.log(greet("Shingles"));// "Hello, Shingles how are you doing today?"
</script>