iT邦幫忙

0

CodeWars : 新手村練等紀錄03- Stop gninnipS My sdroW!

Stop gninnipS My sdroW!

等級:6kyu

原始題目

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (like the name of this kata).
Strings passed in will consist of only letters and spaces.
Spaces will be included only when more than one word is present.

Example:

spinWords("Hey fellow warriors") => "Hey wollef sroirraw" 
spinWords("This is a test") => "This is a test" 
spinWords("This is another test") => "This is rehtona test"

中翻:字串中任何一個字的長度大於或等於5時則反轉該字,反之則輸出一樣的字。

自解:

export class Kata {
  static spinWords(words: string) {
    let arr = words.split(" ");
    arr.forEach((e,index) => {
      if(e.length >= 5 ){
        let reverse = e.split('').reverse().join('');
        arr.splice(index,1,reverse)
      }
    })
    return arr.join(" ")
  }
}

概念:

  1. 先將字串全部拆成一個個字,並存於array中。
  2. 將Array內的每個字逐一檢查是否長度有大於等於5
  3. 若長度大於等於5的,找到該字在Array中的index,並透過splice方法將該值換成reverse過後的值。
    (splice的使用請見下方參考資料)

他解:

author: joewoodhouse

export class Kata {
  static spinWords(words: string) {
    return words
      .split(' ') // Split words up
      .map((w: string) => w.length >= 5 ? w.split('').reverse().join('') : w)
      .join(' '); // Put them back together
  }
}

透過一連串方法,一次將資料處理完畢後直接回傳,非常精簡~
補充w.length >= 5 ? w.split('').reverse().join('') : w
此寫法為Ternary Operator (三元運算子),可以將if else精簡表達出來,有興趣的可以查看看
https://catforcode.com/ternary-operators/

此次題目使用到的方法和參考網址:

array.split()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

array.splice() 可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

(另外補充)三種reverse string的方法
https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/


尚未有邦友留言

立即登入留言