[05.13.22] Coding test

Juyeon.it·2022년 5월 13일
0

Coding test

목록 보기
32/32

Replace With Alphabet Position

Description

In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabetPosition("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" ( as a string )

My answer

function alphabetPosition(text) {
  let alphabets = 'abcdefghijklmnopqrstuvwxyz'.split('');
  
  let result = text.toLowerCase().split('').map(function(letter) {
    return alphabets.includes(letter) ? alphabets.indexOf(letter) + 1 : ' '
  })
  
  return result.filter(a => a != ' ').join(' ');
}

Other solutions

function alphabetPosition(text) {
  var result = "";
  for (var i = 0; i < text.length; i++){
    var code = text.toUpperCase().charCodeAt(i)
    if (code > 64 && code < 91) result += (code - 64) + " ";
  }

  return result.slice(0, result.length-1);
}

Wrap up

charCodeAt method

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

String.charCodeAt(index)

Parameters

index

An integer greater than or equal to 0 and less than the length of the string. If index is not a number, it defaults to 0

Return value

A number representing the UTF-16 code unit value of the character at the given index. If index is out of range, charCodeAt() returns NaN.

Examples

// The following example returns 65, the Unicode value for A.

'ABC'.charCodeAt(0)  // returns 65

source: mdn web docs

0개의 댓글

관련 채용 정보