findThePosition.js (8kyu 87)

Codewars 알고리즘 풀이


Problem

  • When provided with a letter, return its position in the alphabet.
    • 알파벳의 위치를 반환한다.


Solution 01

function findThePosition(letter) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  return 'Position of alphabet: ' + (alphabet.indexOf(letter) + 1);
}

findThePosition('a');  // 1
findThePosition('b');  // 2
findThePosition('c');  // 3
findThePosition('d');  // 4
findThePosition('z');  // 26

indexOf() 메소드

주어진 값이 처음으로 나타나는 위치를 반환한다.

일치하는 값이 없으면 -1을 반환한다.


Solution 02

function findThePosition(letter) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  return `Position of alphabet: ${alphabet.indexOf(letter) + 1}`;
}

findThePosition('a');  // 1
findThePosition('b');  // 2
findThePosition('c');  // 3
findThePosition('d');  // 4
findThePosition('z');  // 26


Solution 03

function findThePosition(letter) {
  const alphabet = '@abcdefghijklmnopqrstuvwxyz';
  return `Position of alphabet: ${alphabet.indexOf(letter)}`;
}

findThePosition('a');  // 1
findThePosition('b');  // 2
findThePosition('c');  // 3
findThePosition('d');  // 4
findThePosition('z');  // 26