Post

랜덤 문자열 생성 함수 리팩토링

랜덤 문자열 생성 함수 리팩토링

랜덤 문자열을 뽑아오는 간단한 함수가 필요해서 만들었다가, 코드가 좀 지저분해 보여서 리팩토링을 진행했다.

처음 버전

처음엔 그냥 타입으로 분기해서 letters / numbers를 따로 관리했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const generateRandomString = (length: number, type: 'letters' | 'numbers'): string => {
  const characterSets = {
    letters: 'abcdefghijklmnopqrstuvwxyz',
    numbers: '0123456789',
  };

  const characters = characterSets[type];
  if (!characters) {
    throw new Error("Invalid type provided. Use 'letters' or 'numbers'.");
  }

  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};

동작은 잘 되지만, 뭔가 깔끔하지가 않았다.

바꾼 버전

그래서 그냥 dictionary객체를 만들어두고, key 값으로 구분하게 바꿔봤다. 이름도 letters, numbers 같은 모호한 이름 말고, a-z, 0-9라는 직관적인 이름으로 바꿨다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const dictionary = {
  'a-z': 'abcdefghijklmnopqrstuvwxyz',
  '0-9': '0123456789',
};

const generateRandomString = (type: 'a-z' | '0-9', length = 4) => {
  const characters = dictionary[type];
  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};

정리

  • 조건 분기 대신 dictionary로 관리 → 코드가 훨씬 깔끔해짐
  • 키 이름도 a-z, 0-9처럼 직관적으로 바꿔서 가독성 ↑
  • 나중에 대문자나 특수문자도 쉽게 추가 가능
This post is licensed under CC BY 4.0 by the author.