文章目录
codewars-js练习
2021/2/16
github 地址
【1】<8kyu>【Transportation on vacation】
Every day you rent the car costs $40. If you rent the car for 7 or more days, you get $50 off your total. Alternatively, if you rent the car for 3 or more days, you get $20 off your total.
Write a code that gives out the total amount for different days(d).
你租这辆车每天要花40美元。如果你租车7天或更长时间,你可以得到50美元的折扣。或者,如果你租车3天以上,你可以得到20美元的折扣
example:
rentalCarCost(1), 40)
rentalCarCost(2), 80)
rentalCarCost(5), 180)
rentalCarCost(10), 350)
solution
<script type="text/javascript">
function rentalCarCost(d) {
// console.log(d);
if(d >=7){
return (d*40)-50;
}else if(d >= 3 && d <7){
return (d*40)-20;
}else{
return d*40;
}
}
// 验证
console.log(rentalCarCost(1));//40
console.log(rentalCarCost(10));//350
console.log(rentalCarCost(5));//180
console.log(rentalCarCost(3));//100
</script>
【2】<8kyu>【Century From Year】
The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc.
Given a year, return the century it is in.
第一个世纪从公元1年到公元100年,第二,从公元101年到公元200年,等等。
example:
centuryFromYear(1705) returns (18)
centuryFromYear(1900) returns (19)
centuryFromYear(1601) returns (17)
centuryFromYear(2000) returns (20)
solution
<script type="text/javascript">
function century(year) {
// console.log(year);
return Math.ceil(year/100);
}
// 验证
console.log(century(1705));//18
console.log(century(1900));//19
console.log(century(1601));//17
console.log(century(2000));//20
console.log(century(89));//1
</script>
【3】<8kyu>【Function 3 - multiplying two numbers】
Implement a function which multiplies two numbers.
example:
2*3 = 6
solution
<script type="text/javascript">
function multiply(a,b){
return a*b;
}
// 验证
console.log(multiply(2, 3));// 6
</script>
【4】<8kyu>【Filter out the geese】
Write a function, gooseFilter
/goose_filter
/GooseFilter
, that takes an array of strings as an argument and returns a filtered array containing the same elements but with the ‘geese’ removed.
The geese are any strings in the following array, which is pre-populated in your solution:
var geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbache"];
编写一个函数gooseFilter/goose_filter/ gooseFilter,它接受一个字符串数组作为参数,并返回一个过滤后的数组,该数组包含相同的元素,但去掉了’geese’。
example:
["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]//["Mallard", "Hook Bill", "Crested", "Blue Swedish"]
solution
<script type="text/javascript">
function gooseFilter (birds) {
var geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"];
// console.log(birds);
for(var i=0;i<birds.length;i++){
for(var j=0;j<geese.length;j++){
if(birds[i] == geese[j]){
birds.splice(i,1);
i=i-1;
}
}
}
return birds;
};
// 验证
console.log(gooseFilter(["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]));// ["Mallard", "Hook Bill", "Crested", "Blue Swedish"]
</script>
以上为自己思路供大家参考,可能有更优的思路。