본문 바로가기

IT/JavaScript

Object, Array each 함수

Object? Array?

forEach는 Array만 돌릴 수 있기 때문에 반복문을 돌릴려면 Object.keys(obj).forEach 뭐 이런 식으로 돌려야 하기 때문에 체이닝이 매우 많아진다.

그래서 Array이든 Object든 forEach를 돌릴 수 있게 구현해봤다.

function each<T>(
  target: Array<T> | Type.HashType<T>,
  cb: (item: T, key: string | number) => any
): void {
  if (!isFunction(cb)) return;
  match(target)
    .on(
      () => isArray(target) === true,
      () => {
        const arr: Array<T> = target as Array<T>;
        arr.forEach((item: T, idx: number) => cb(item, idx));
      }
    )
    .on(
      () => isObject(target) === true,
      () => {
        const object: Type.HashType<T> = target as Type.HashType<T>;
        Object.keys(object).forEach((key: string) => {
          cb(object[key], key);
        });
      }
    )
    .otherwise((target) => new Error(`The target is not iterable ${target}`));
}

그냥 target이 Object인지 Array인지에 따라서 적절하게 forEach를 돌려주는 util 함수이다.

'IT > JavaScript' 카테고리의 다른 글

Request body validation middleware  (0) 2023.05.08
if를 통한 명확하고 확실한 조건 처리  (0) 2023.04.14
TypeScript 타입 단언  (0) 2023.02.21
TypeScript 타입 추론  (0) 2023.01.08
axios  (0) 2022.10.08