Как работает троичный оператор в функции? - PullRequest
0 голосов
/ 02 октября 2018

Можете ли вы объяснить мне строку возврата в этом алгоритме?

Функция должна взять строку и вернуть ее версию Pig Latin, которая состоит в том, что она берет первый согласный или согласный кластер и помещает его вконец строки, добавляющий «ay» в конце.

Если строка начинается с гласной, то в конце следует добавить «way».

function translatePigLatin(str) {
  function check(obj) {
      return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj;
  }

  return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay');
}

// test here
translatePigLatin("consonant"); // should return "onsonantcay"

Ответы [ 3 ]

0 голосов
/ 02 октября 2018

Надеюсь, что приведенный ниже код объясняет это комментариями.

function translatePigLatin(str) {
  function check(obj) {
      return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj;
  }

  //return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay');
  // The above is explained as equivalent to below:
  
  if(check(0) === 0){
    return str.substr(check(0)).concat('w'+'ay')
  }
  return str.substr(check(0)).concat(str.substr(0, check(0))+'ay')
}

// test here
console.log(translatePigLatin("consonant")); // should return "onsonantcay"
0 голосов
/ 02 октября 2018

Обычно полезно разбить троичные операторы на блоки if / else в тех случаях, когда вы не знаете, что они делают.

function translatePigLatin(str) {
  function check(index) {
      // return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj;
      // break down ternary into traditional if also changed obj to index to be more descriptive
      const vowels = ['a','i','u','e','o'];
      // if the character at the given index exists then check the next character
      if (vowels.indexOf(str.charAt(index)) === -1) {
        return check(index + 1)
      }
      // otherwide return index (vowel case)
      return index;
  }

  // return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay');
  // set base translated word as the first letter in word that is not a vowel.
  const indexKey = check(0)
  // get string after index key
  let substringed = str.substr(indexKey)
  // get string from beginning until indexkey
  let appended = str.substr(0, indexKey);
  // if the index key is the first letter (word starts with vowel) use 'w'
  if (indexKey === 0) {
    appended = 'w';
  }
  // return string
  return `${substringed}${appended}ay`;
}

// test here
const singleConsonant = translatePigLatin("constant");
const doubleConsonant = translatePigLatin("chain");
const vowel = translatePigLatin("analyze")
console.log(singleConsonant, doubleConsonant, vowel);
0 голосов
/ 02 октября 2018

Это трудно понять, потому что имена ужасны.obj на самом деле число, используемое для перехода к позиции в строке, поэтому его лучше назвать pos или что-то в этом роде.check ничего не проверяет, просто перемещается вперед, пока не будет найден первый гласный, поэтому должно быть:

 const firstVowel = (pos = 0) => "aeiou".includes(str.charAt(pos)) ? pos : firstVowel(pos + 1);

Теперь последняя строка просто берет часть из первого гласного (удаляет согласные в начале):

 str.substr(/*from*/ firstVowel() /*till end*/)

Если первый гласный находится непосредственно в начале:

 firstVowel() === 0

, он просто добавляет

 "way"

, иначе он принимает эти согласные в начале:

 str.substr(0, /*to*/ firstVowel())

и добавляет "y".

...