[04.21.22] Coding test

Juyeon.it·2022년 4월 21일
0

Coding test

목록 보기
10/32

The Hashtag Generator

Description

The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return false.
If the input or the result is an empty string it must return false.
Examples
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false

My answer

function generateHashtag (str) {
  if (str.trim().length == 0) { return false };
  let result = '#' + str.split(' ').map(function(a) {
    return a = a.charAt(0).toUpperCase() + a.slice(1)
  }).join('');
  return (result.length > 140) ? false : result;
}

Other solutions

function generateHashtag (str) {
  return str.length > 140 || str === '' ? false :
    '#' + str.split(' ').map(capitalize).join('');
}
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Extract the domain name from a URL

Description

Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:

My answer

function domainName(url){
  let target = url;
  let index;
  if (target.includes('//')) {
    target = target.split('//')[1];
    index = 0;
  };
  if (target.includes('www')) {
    index = 1;
  };
  if (!target.includes('//') && !target.includes('www')){
    index = 0;
  };
  return target.split('.')[index];
}

Other solutions

function domainName(url){
  url = url.replace("https://", '');
  url = url.replace("http://", '');
  url = url.replace("www.", '');
  return url.split('.')[0];
};
function domainName(url){
  return url.match(/(?:http(?:s)?:\/\/)?(?:w{3}\.)?([^\.]+)/i)[1];
}

Split Strings

Description

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:

  • 'abc' => ['ab', 'c_']
  • 'abcdef' => ['ab', 'cd', 'ef']

My answer

function solution(str){
  let result = [];
  let string = str;
  
  if (str.length % 2 != 0) { string = str + '_' }
  
  for (let i = 0; i < string.length; i = i+2) {
    result.push(string[i]+string[i+1])
  };
  
  return result;
}

Other solutions

function solution(s){
   return (s+"_").match(/.{2}/g)||[]
}
function solution(str){
  arr = [];
  for(var i = 0; i < str.length; i += 2){
    second = str[i+1] || '_';
    arr.push(str[i] + second);
  }
  return arr;
}

0개의 댓글

관련 채용 정보