<!-- {%hackmd BJrTq20hE %} --> <!-- {%hackmd hackmd-dark-theme %} --> # 8 kyu ### [Grasshopper - Summation](https://www.codewars.com/kata/55d24f55d7dd296eb9000030) :::spoiler 解法 ``` javascript= let summation = function (num) { let sum = 0; for(let i = 1; i<=num; i++){ sum+=i; } return sum; } ``` ::: ### [Reversed Strings](https://www.codewars.com/kata/5168bb5dfe9a00b126000018) :::spoiler 解法 ``` javascript= function solution(str){ return str.split("").reverse().join(""); } ``` ```javascript= let str = "abcdefg"; str = str.split(""); console.log(str); // ['a', 'b', 'c', 'd', 'e', 'f', 'g'] str = str.reverse(); console.log(str); // ['g', 'f', 'e', 'd', 'c', 'b', 'a'] str = str.join(""); console.log(str); // gfedcba // str = str.join(" + "); // console.log(str); // g + f + e + d + c + b + a ``` ::: ### [Count by X](https://www.codewars.com/kata/5513795bd3fafb56c200049e) :::spoiler 解法 ``` javascript= function countBy(x, n) { let z = []; for(let i = 1; i<=n ; i++){ let pushNum = x * i; z.push(pushNum); } return z; } ``` ::: ### [Beginner - Reduce but Grow](https://www.codewars.com/kata/57f780909f7e8e3183000078) :::spoiler 解法 ``` javascript= function grow(x){ let result = 1; x.forEach(item=>{ result *= item; }) return result; } // const grow=x=> x.reduce((a,b) => a*b); ``` ::: ### [Convert boolean values to strings 'Yes' or 'No'.](https://www.codewars.com/kata/53369039d7ab3ac506000467) :::spoiler 解法 ``` javascript= function boolToWord( bool ){ return bool ? "Yes" : "No"; } ``` ::: ### [Will there be enough space?](https://www.codewars.com/kata/5875b200d520904a04000003) :::spoiler 解法 ``` javascript= function enough(cap, on, wait) { let empty = cap - on - wait; return empty >= 0 ? 0 : Math.abs(empty) } // function enough(cap, on, wait) { // return Math.max(wait + on - cap, 0); // } ``` ::: ### [Abbreviate a Two Word Name](https://www.codewars.com/kata/57eadb7ecd143f4c9c0000a3)* - 知識點:[Array.prototype.map()](https://www.codewars.com/kata/57eadb7ecd143f4c9c0000a3) :::spoiler 解法 - 該題傳入的值也會有單字開頭是小寫的情況 ``` javascript= function abbrevName(name){ return name.split(" ").map((c)=> c[0].toUpperCase()).join("."); } ``` ::: ### [Sum without highest and lowest number](https://www.codewars.com/kata/576b93db1129fcf2200001e6)*** - 知識點:!!轉布林、null型別、[Array.prototype.reduce()](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)、Math.min :::spoiler 解法 - 注意測試值包含 null ,null 為 object,所以只能是兩個等號 ``` javascript= function sumArray(array) { if (array == null || array.length <= 2) { return 0; } array.sort((a, b) => { return a - b; }); array = array.slice(1, array.length - 1); return array.reduce((a, c) => a + c); // function sumArray(array) { // return Array.isArray(array) && array.length > 1 // ? array.reduce((s, n) => s + n, 0) - Math.min(...array) - Math.max(...array) // : 0 // } } ``` - !!轉為布林,單個!結果會相反 ```javascript= function sumArray(array) { return !!array; } console.log(sumArray(null)); // false console.log(sumArray([])); // true console.log(sumArray([-6, 20, -1, 10, -12])); // true ``` ::: ### [Beginner Series #1 School Paperwork](https://www.codewars.com/kata/55f9b48403f6b87a7c0000bd)* - 知識點: :::spoiler 解法 ``` javascript= function paperwork(n, m) { return n > 0 && m > 0 ? n * m : 0; } ``` ::: ### [Sum Arrays](https://www.codewars.com/kata/53dc54212259ed3d4f00071c)* - 知識點:Array.prototype.reduce() :::spoiler 解法 - 注意傳入 [] 要回傳 0 ,需要給初始值 ``` javascript= function sum (numbers) { "use strict"; return numbers.reduce((a,c)=>a+c,0); }; ``` ::: ### [Convert a Number to a String!](https://www.codewars.com/kata/5265326f5fda8eb1160004c8)** - 知識點:數字轉字串的各種方法 :::spoiler 解法 ``` javascript= function numberToString(num) { return num.toString(); } function numberToString(num) { // Return a string of the number here! return String(num); } function numberToString(num) { return ''+num; } const numberToString = num => `${num}`; ``` - 此程式碼旨在執行toString()(對於整數)的操作,但不使用內建函數。 ```javascript= function numberToString(num) { //create a new empty string in which the result will be written var str = ''; //Check, whether the number is positive or negative. The multiplier 1 or -1 will be saved for later const mult = num < 0 ? -1 : 1; //Take the absolut value of num. Could also be done with Math.abs num *= mult; //Loop, which will run as often as num has digits do { //Take the least significant digit of num (num % 10), add 48 and get the associated ascii character. The number 0 has the ascii value of 48, 1 = 49... 9 = 57. //Then prepend that character to the string. str = String.fromCharCode(num % 10 + 48) + str; //Remove the least significant digit from num. (Divide by ten, then round down) num = ~~(num / 10); } while (num > 0); //If the input number was negative, prepend a -. if(mult < 0) str = "-" + str; return str; } ``` ::: ### [Sentence Smash](https://www.codewars.com/kata/53dc23c68a0c93699800041d)* - 知識點:Array.prototype.join() :::spoiler 解法 ```javascript= function smash (words) { return words.join(" "); }; ``` ::: ### [Calculate average](https://www.codewars.com/kata/57a2013acf1fa5bfc4000921)**** - 知識點:Array.prototype.reduce() :::spoiler 解法 - 要用`array.length === 0`來檢查是否為空陣列,而非`array === []`,會報錯,不能使用===運算符來比較兩個陣列是否相等 ``` javascript= function findAverage(array) { if (array.length == 0) { return 0; } else { return array.reduce((a, c) => a + c) / array.length; } } console.log(findAverage([])); ``` ::: ### [Even or Odd](https://www.codewars.com/kata/53da3dbb4a5168369a0000fe)* - 知識點:% :::spoiler 解法 ``` javascript= function evenOrOdd(number) { return number % 2 === 0 ? "Even" : "Odd" } ``` ::: ### [Basic Mathematical Operations](https://www.codewars.com/kata/57356c55867b9b7a60000bd7)** - 知識點:switch :::spoiler 解法 ``` javascript= function basicOp(operation, value1, value2) { switch (operation) { case "+": return value1 + value2; case "-": return value1 - value2; case "*": return value1 * value2; case "/": return value1 / value2; } } ``` ::: ### [Thinkful - Logic Drills: Traffic light](https://www.codewars.com/kata/58649884a1659ed6cb000072)* - 知識點:用陣列處理、三元運算子、物件解法 :::spoiler 解法 ``` javascript= function updateLight(current) { const trafficLight = ["green", "yellow", "red"]; return current === "red" ? trafficLight[0] : trafficLight[trafficLight.indexOf(current) + 1]; } console.log(updateLight("green")); console.log(updateLight("yellow")); console.log(updateLight("red")); ``` ```javascript= // 物件解法 const updateLight = current => ({ green: 'yellow', yellow: 'red', red: 'green', })[current] ``` ::: ### [Keep Hydrated!](https://www.codewars.com/kata/582cb0224e56e068d800003c)*** - 知識點:Math.floor() :::spoiler 解法 ``` javascript= function litres(time) { return Math.floor(time * 0.5); } ``` ::: ### [Remove String Spaces](https://www.codewars.com/kata/57eae20f5500ad98e50002c5)* - 知識點:正則、[String.prototype.replace()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace) :::spoiler 解法 ``` javascript= function noSpace(x){ return x.replace(/\s/g,"") } ``` ```javascript= function noSpace(x){return x.split(' ').join('')} ``` ::: ### [The Feast of Many Beasts](https://www.codewars.com/kata/5aa736a455f906981800360d)* - 知識點:[String.prototype.slice()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/slice)為負值的話是從尾部開始算、startsWith、endsWith :::spoiler 解法 ``` javascript= function feast(beast, dish) { return beast[0] === dish[0] && beast[beast.length - 1] === dish[dish.length - 1] } ``` ```javascript= function feast(beast, dish) { return beast[0]===dish[0] && beast.slice(-1)===dish.slice(-1); } ``` ```javascript= function feast(beast, dish) { return dish.startsWith(beast[0]) && dish.endsWith(beast[beast.length-1]) } ``` ::: ### [String cleaning](https://www.codewars.com/kata/57e1e61ba396b3727c000251)** - 知識點:正則,\d 為匹配數字 :::spoiler 解法 ``` javascript= function stringClean(s){ return s.replace(/\d/g, "") } ``` ::: ### [Is the string uppercase?](https://www.codewars.com/kata/56cd44e1aa4ac7879200010b)*** - 知識點:String.prototype.match() 若沒匹配到會回傳 null :::spoiler 解法 ``` javascript= String.prototype.isUpperCase = function() { const regex = /[a-z]/g; return this.match(regex) === null; } ``` ::: ### [Stringy Strings](https://www.codewars.com/kata/563b74ddd19a3ad462000054)** - 知識點:String.prototype.repeat()、String.prototype.padStart() :::spoiler 解法 ``` javascript= function stringy(size) { const pair = "10"; const pairs = pair.repeat(Math.floor(size / 2)); return size % 2 === 1 ? pairs + 1 : pairs; } ``` ```javascript= const stringy = size => "10".repeat(size).slice(0,size); ``` ```javascript= const stringy = x => ''.padStart(x,'10'); ``` ::: ### [Training JS #8: Conditional statement--switch](https://www.codewars.com/kata/572059afc2f4612825000d8a)** - 知識點:switch 多 case 執行相同程式碼 :::spoiler 解法 ``` javascript= function howManydays(month) { var days; switch (month) { case 2: days = 28; break; case 4: case 6: case 9: case 11: days = 30; break; default: days = 31; } return days; } howManydays(12); ``` ::: ### [Will you make it?](https://www.codewars.com/kata/5861d28f124b35723e00005e)* - 知識點: :::spoiler 解法 ``` javascript= const zeroFuel = (distanceToPump, mpg, fuelLeft) => { return distanceToPump <= mpg * fuelLeft; }; ``` ::: ### [Counting sheep...](https://www.codewars.com/kata/54edbc7200b811e956000556)* - 知識點: :::spoiler 解法 ``` javascript= function countSheeps(sheep) { let sheepCount = 0; sheep.forEach(e => e === true ? sheepCount++ : sheepCount) return sheepCount } ``` ::: ### [I love you, a little , a lot, passionately ... not at all](https://www.codewars.com/kata/57f24e6a18e9fad8eb000296)*** - 知識點:調換陣列順序 :::spoiler 解法 ``` javascript= function howMuchILoveYou(nbPetals) { const phrases = [ "I love you", "a little", "a lot", "passionately", "madly", "not at all", ]; return phrases[nbPetals % 6 === 0 ? phrases.length - 1 : (nbPetals % 6) - 1]; } ``` ```javascript= function howMuchILoveYou(nbPetals) { const phrases = [ "not at all", "I love you", "a little", "a lot", "passionately", "madly", ]; return phrases[nbPetals % 6]; } ``` ::: ### [Rock Paper Scissors!](https://www.codewars.com/kata/5672a98bdbdd995fad00000f)** - 知識點:物件寫法 :::spoiler 解法 ``` javascript= const rps = (p1, p2) => { if (p1 === p2) return "Draw!"; if (p1 === "scissors") { if (p2 === "rock") { return "Player 2 won!"; } else if (p2 === "paper") { return "Player 1 won!"; } } if (p1 === "rock") { if (p2 === "scissors") { return "Player 1 won!"; } else if (p2 === "paper") { return "Player 2 won!"; } } if (p1 === "paper") { if (p2 === "scissors") { return "Player 2 won!"; } else if (p2 === "rock") { return "Player 1 won!"; } } }; ``` ```javascript= const rps = (p1, p2) => { if (p1 === p2) return "Draw!"; var rules = {rock: "scissors", paper: "rock", scissors: "paper"}; if (p2 === rules[p1]) { return "Player 1 won!"; } else { return "Player 2 won!"; } }; ``` ::: ### [Return Negative](https://www.codewars.com/kata/55685cd7ad70877c23000102)* - 知識點: :::spoiler 解法 ``` javascript= function makeNegative(num) { return num < 0 ? num : -num; } ``` ::: ### [Correct the mistakes of the character recognition software](https://www.codewars.com/kata/577bd026df78c19bca0002c0)*** - 知識點: :::spoiler 解法 ``` javascript= function correct(string) { const arr = string.split(""); arr.forEach((e, i) => { switch (e) { case "5": arr[i] = "S"; break; case "0": arr[i] = "O"; break; case "1": arr[i] = "I"; break; } }); return arr.join(""); } correct("51NGAP0RE"); ``` ```javascript= correct = s => s.replace(/0/g,'O').replace(/1/g,'I').replace(/5/g,'S') ``` ```javascript= const corrections = { '5': 'S', '0': 'O', '1': 'I', }; const correct = string => ( string.replace(/[501]/g, character => corrections[character]) ); ``` ::: ### [Count Odd Numbers below n](https://www.codewars.com/kata/59342039eb450e39970000a6)** - 知識點: :::spoiler 解法 ``` javascript= function oddCount(n){ return n%2 === 1 ? (n-1)/2 : n/2 } ``` ```javascript= const oddCount = n => Math.floor(n/2) ; ``` ::: ### [Find Maximum and Minimum Values of a List](https://www.codewars.com/kata/577a98a6ae28071780000989)* - 知識點: :::spoiler 解法 ``` javascript= var min = function(list){ return Math.min(...list); } var max = function(list){ return Math.max(...list); } ``` ::: ### [Count of positives / sum of negatives](https://www.codewars.com/kata/576bb71bbbcf0951d5000044)** - 知識點:空陣列 [] 是真值 :::spoiler 解法 ``` javascript= function countPositivesSumNegatives(input) { if (!input || input.length === 0) return []; const arr = []; arr[0] = input.filter((e) => e > 0).length; arr[1] = input.filter((e) => e < 0).reduce((a, c) => a + c, 0); return arr; } countPositivesSumNegatives([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, ]); ``` ::: ### [To square(root) or not to square(root)](https://www.codewars.com/kata/57f6ad55cca6e045d2000627)** - 知識點: :::spoiler 解法 ``` javascript= function squareOrSquareRoot(array) { return array.map((e) => Number.isInteger(Math.sqrt(e)) ? Math.sqrt(e) : Math.pow(e, 2) ); } console.log(squareOrSquareRoot([4, 3, 9, 7, 2, 1])); ``` ::: ### [ASCII Total](https://www.codewars.com/kata/572b6b2772a38bc1e700007a)* - 知識點: :::spoiler 解法 ``` javascript= function uniTotal (string) { return string.split("").reduce((a,c)=> a+ c.charCodeAt(0),0); } ``` ::: ### [Flick Switch](https://www.codewars.com/kata/64fbfe2618692c2018ebbddb)** - 知識點: :::spoiler 解法 ``` javascript= function flickSwitch(arr){ let state = true; return arr.map(e=>{ if(e === "flick"){ state = !state; return state; }else{ return state; } }) } ``` ::: ### [Gravity Flip](https://www.codewars.com/kata/5f70c883e10f9e0001c89673)** - 知識點: :::spoiler 解法 ``` javascript= const flip=(d, a)=>{ switch(d){ case "R": a.sort((a,b)=> a-b); break; case "L": a.sort((a,b)=> b-a); break; } return a } ``` ```javascript= const flip = (d, a) => a.sort((x, y) => d === 'R' ? x - y : y - x); ``` ::: ### [FIXME: Replace all dots](https://www.codewars.com/kata/596c6eb85b0f515834000049)** - 知識點: :::spoiler 解法 ``` javascript= var replaceDots = function(str) { return str.replace(/\./g, '-'); } ``` ::: ### [Add Length](https://www.codewars.com/kata/559d2284b5bb6799e9000047)* - 知識點: :::spoiler 解法 ``` javascript= function addLength(str) { const arr = str.split(" "); return arr.map((e) => e + " " + e.length); } ``` ::: ### [String Templates - Bug Fixing #5](https://www.codewars.com/kata/55c90cad4b0fe31a7200001f)** - 知識點: :::spoiler 解法 ``` javascript= function buildString(...template){ return `I like ${template.join(', ')}!`; } ``` ::: ### [Who is going to pay for the wall?](https://www.codewars.com/kata/58bf9bd943fadb2a980000a7)** - 知識點: :::spoiler 解法 ``` javascript= function whoIsPaying(name){ if(name.length<=2) return [name]; return [name,name[0]+name[1]]; } ``` ::: ### [Removing Elements](https://www.codewars.com/kata/5769b3802ae6f8e4890009d2)* - 知識點: :::spoiler 解法 ``` javascript= function removeEveryOther(arr){ const resultArr =[] for(let i = 0; i < arr.length; i+=2){ resultArr.push(arr[i]); } return resultArr; } ``` ```javascript= function removeEveryOther(arr){ return arr.filter(function(elem, index) { return index % 2 === 0; }); } ``` ::: ### [Chuck Norris VII - True or False? (Beginner)](https://www.codewars.com/kata/570669d8cb7293a2d1001473)* - 知識點:其他網友解法頗有趣XDD :::spoiler 解法 ``` javascript= function ifChuckSaysSo(){ return !true; } ``` ::: ### [Merge two sorted arrays into one](https://www.codewars.com/kata/5899642f6e1b25935d000161)** - 知識點:Set :::spoiler 解法 ``` javascript= function mergeArrays(arr1, arr2) { const arr = []; arr1.forEach((e) => arr.push(e)); arr2.forEach((e) => arr.push(e)); arr.sort((a, b) => a - b); const result = new Set(arr); return [...result]; } ``` ```javascript= function mergeArrays(arr1, arr2) { return Array.from(new Set(arr1.concat(arr2).sort((a,b) => (a-b)))); } ``` ::: ### [title]()** - 知識點: :::spoiler 解法 ``` javascript= ``` :::
{"description":":::","title":"Codewars 8kyu","contributors":"[{\"id\":\"65ef09e4-76a5-4ffa-8afd-4e2465c6240e\",\"add\":20883,\"del\":4180}]"}
Expand menu