본문 바로가기
알고리즘/Codewars

[Codewars] Split Strings (6 kyu) / JavaScript

by fluss 2023. 1. 6.

https://www.codewars.com/kata/515de9ae9dcfc28eb6000001

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

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']
 

코드

function solution(str){
  const result = [];
  for(let i = 0; i < str.length; i += 2){
    let s = str.slice(i, 2 + i);
    result.push(s.padEnd(2, '_'));
  }
  return result
}

댓글