import 없이 함수 호출하기

유영석·2022년 2월 28일
3

자주 사용하는 함수를 더 편리하게 사용할 방법은 없을까?
프론트앤드 개발을 하다보면, 여러가지 데이터에 대하여 서로 다른 형태로 표기해야할 일이 많이 있다.
예를들어 Date는 너무나 다양한 방법으로 표기가 가능하다.

  • YYYY.MM.DD
  • MM.DD hh.mm
  • x days ago
  • ...

이렇게 백앤드로부터 받는 데이터는 string(혹은 number) type이다.

{
  createdAt: "2021-04-21T01:00:59", // ISOString
  sentTime: 1645933201, // second
}

편리하게 우리가 원하는 데이터로 가공할 방법은 없을까?
보통 이러한 형태의 데이터를 Backend에서 받아오고 가공하는 함수를 만들어 처리할 것이다.

// util.ts
import moment from 'moment';

// string(ISOString) to YYYY.MM.DD
export function toDateDisplay(dateString: string){
  const date = new Date(dateString);

  if (date instanceof Date && !isNaN(date.getTime()))
    return moment(date).format('YYYY.MM.DD');
  else {
    if (this !== '') console.warn(`[${this}] Invalid Date.`);
    return '';
  }
}

// other.ts
import { toDateDisplay } from '~/util';
  
class Something {
  ...
  createdAt: string;
  updatedAt: string;
  ...
}
  
const data = await fetch(...);
const something = new Something(data);

toDateDisplay(something.createdAt);

// another.ts
import { toDateDisplay } from '~/util';

...
toDateDisplay(something.createdAt);
...

매번 import 해서 불러오는게 가장 좋은 방법일까?
어떻게해야 더 효율적으로 변경할 수 있을까?
여기서 나는 string에 prototype을 확장하여 해결하고자 한다.

이 방법은 관점에 따라 유연하며 실용적일 수 있지만, 원시데이터 타입에 기능을 추가하는 것이기 때문에 불편하다고 생각하실 수 있습니다.

// index.d.ts
declare global {
  interface String {
    toDateDisplay: () => string; // YYYY.MM.DD
  }
}

// index.ts
import moment from 'moment';

String.prototype.toDateDisplay = function (this: string) {
  const date = new Date(this);

  if (date instanceof Date && !isNaN(date.getTime()))
    return moment(date).format('YYYY.MM.DD');
  else {
    if (this !== '') console.warn(`[${this}] Invalid Date.`);
    return '';
  }
};
// 기존 함수 호출
import { toDateDisplay } from '~/util';

toDateDisplay(something.createdAt); // YYYY.MM.DD
// prototype 추가
something.createdAt.toDateDisplay(); // YYYY.MM.DD

위와 같이 String의 Prototype에 함수를 추가하여 Date 표기를 위한 함수를 추가했다. 원시 데이터 타입에 함수를 추가하여 불편할 수는 있지만, 편의성을 제공한다는 관점에서는 사용해볼만하다고 생각한다. 하지만 원시타입에 함수를 추가하는 것이므로 남발하지 않도록 자제해야 한다.

profile
ENFP FE 개발자 :)

2개의 댓글

comment-user-thumbnail
2022년 3월 8일

전역변수를 쓸까? 말까?에 대한 고민과 비슷하네요.
사용하면 편리하지만, 남용하면 문제가 될 소지가 있죠.

1개의 답글