Javascript util 함수들

박상은·2021년 12월 9일
0

🎁 분류 🎁

목록 보기
4/16

직접 만들어 본 util 함수들
typescript 버전이랑 여러 가지 추가하기

1. 랜덤한 더미데이터

database에 랜덤한 유저 생성해야 할 때 사용
1. 성명 ( 한국 기준 )
2. 지역 ( 한국 기준 100개중 랜덤 )
3. 휴대폰 번호 ( 010으로 시작함 )
4. 이메일 ( 5 ~ 10자리 )
5. 생일 ( 1990년생 ~ 2010년생까지 )

const firstNameList = "김이박최정강조윤장임한오서신권황안송류전홍고문양손배조백허유남심노정하곽성차주우구신임라전민유진지엄채원천방공강현함변염양변여추노도소신석선설마길주연방위표명기반왕금옥육인맹제모장남탁국여진어은편구용";
const lastNameList = "민준서예도윤시우주원하지호후현훈건진선재연유정승혁은환찬성영수동태규한결이안온율빈람석양희완강경";
const alphaList = "abcdefghijklmnopqrstuvwxyz";
const numberList = "0123456789";
const emailList = ["naver.com", "gmail.com", "daum.net", "kakao.com", "nate.com", "tistory.com", "outlook.com"];
const cityList = ["서울특별시", "부산광역시", "인천광역시", "대구광역시", "대전광역시", "광주광역시", "울산광역시", "경기도 수원시", "경기도 고양시", "경기도 용인시",
                  "경상남도 창원시", "경기도 성남시", "충청북도 청주시", "경기도 부천시", "경기도 화성시", "경기도 남양주시", "전라북도 전주시", "충청남도 천안시", "경기도 안산시", "경기도 안산시",
                  "경기도 안양시", "경상남도 김해시", "경기도 평택시", "경상북도 포항시", "제주특별자치도 제주시", "경기도 시흥시", "경기도 파주시", "경기도 의정부시", "경기도 김포시", "경상북도 구미시",
                  "경기도 광주시", "경상남도 양산시", "강원도 원주시", "경상남도 진주시", "세종특별자치시", "경기도 광명시", "충청남도 안산시", "전라북도 익산시", "강원도 춘천시", "경상북도 경산시",
                  "경기도 군포시", "전라북도 군산시", "경기도 하남시", "전라남도 여수시", "전라남도 순천시", "경상북도 경주시", "경상남도 거제시", "전라남도 목포시", "경기도 오산시", "경기도 이천시",
                  "강원도 강릉시", "경기도 양주시", "충청북도 충주시", "경기도 안성시", "경기도 구리시", "충청남도 서산시", "제주특별자치도 서귀포시", "충청남도 당진시", "경상북도 안동시", "경기도 포천시",
                  "경기도 의왕시", "전라남도 광양시", "경상북도 김천시", "충청북도 제천시", "경상남도 통영시", "충청남도 논산시", "경상북도 칠곡군", "경상남도 사천시", "경기도 여주시", "충청남도 공주시",
                  "경기도 양평군", "전라북도 정읍시", "경상북도 영주시", "전라남도 나주시", "충청북도 음성군", "경상남도 밀양시", "충청남도 홍성군", "충청남도 보령시", "전라북도 완주군", "경상북도 상주시",
                  "경상북도 영천시", "경기도 동두천시", "강원도 동해시", "전라북도 김제시", "전라남도 무안군", "전라북도 남원시", "충청북도 진천군", "충청남도 예산군", "강원도 속초시", "경상북도 문경시",
                  "경상남도 함안군", "강원도 삼척시", "강원도 홍천군", "전라남도 해남군", "충청남도 부여군", "경상남도 창녕군", "충청남도 태안군", "전라남도 고흥군", "전라남도 화순군", "경상남도 거창군"
                ];

// 랜덤한 이름 생성기
export const generatorDummyName = (number = 10) => {
  const nameList = Array(number).fill().map(() => {
    const firstName = firstNameList[Math.floor(Math.random() * firstNameList.length)];
    const lastName = lastNameList[Math.floor(Math.random() * lastNameList.length)] + lastNameList[Math.floor(Math.random() * lastNameList.length)];

    return firstName + lastName;
  });

  return nameList;
};

// 랜덤한 지역 생성기
export const generatorDummyCity = (number = 10) => Array(number).fill().map(() => cityList[Math.floor(Math.random() * cityList.length)]);

// 랜덤한 휴대폰 번호 생성기
export const generatorDummyPhoneNumber = (number = 10) => {
  const phoneNumberList = Array(number).fill().map(() => {
    let tempList = "010";
    for(let i = 0; i< 8; i++){
      tempList += numberList[Math.floor(Math.random() * numberList.length)];
    }

    tempList = tempList.slice(0, 3) + "-" + tempList.slice(3, 7) + "-" + tempList.slice(7);

    return tempList;
  });

  return phoneNumberList;
};

// 랜덤한 이메일 생성기
export const generatorDummyEmail = (number = 10) => {
  const Emails = Array(number).fill().map(() => {
    let temp = "";

    // 이메일 길이 5 ~ 10
    const emailLength = Math.floor(Math.random() * 5) + 5;

    // 이메일에서 @앞부분 정의
    for(let i = 0; i< emailLength; i++){
      // 영어 or 숫자 랜덤 지정
      const alphaOrNumber = Math.floor(Math.random() * 2);

      temp += alphaOrNumber ? alphaList[Math.floor(Math.random() * alphaList.length)] : numberList[Math.floor(Math.random() * numberList.length)];
    }

    temp += "@";

    temp += emailList[Math.floor(Math.random() * emailList.length)]

    return temp;
  });

  return Emails;
};

// 랜덤한 생일 생성기
export const generatorDummyBirthday = (number = 10) => {
  const yearList = Array(20).fill().map((v, i) => i + 90 >= 100 ? "0" + (i - 10) : i + 90).map(v => v + "");
  const monthList = Array(12).fill().map((v, i) => i < 9 ? "0" + (i + 1) : "" + (i + 1));
  const dayList = Array(31).fill().map((v, i) => i < 10 ? "0" + (i + 1) : "" + (i + 1));

  return Array(number).fill().map(() => yearList[Math.floor(Math.random() * yearList.length)] + monthList[Math.floor(Math.random() * monthList.length)] + dayList[Math.floor(Math.random() * dayList.length)]);
};

2. 시간포멧

// 날짜로 변환
function dateFormat(value, form) {
  const date = new Date(value);

  const dateArray = [];
  let result = "";
  const decorationArray = form.match(/[^YMDhms]/g);
  let decorationIndex = 0;

  dateArray.push(yearFormat(date, form));
  dateArray.push(monthFormat(date, form));
  dateArray.push(dayFormat(date, form));
  dateArray.push(hourFormat(date, form));
  dateArray.push(minuteFormat(date, form));
  dateArray.push(secondFormat(date, form));

  dateArray.forEach(v => {
    if (!v) return;

    const decoration = decorationArray[decorationIndex] ? decorationArray[decorationIndex] : "";
    decorationIndex += 1;

    result += `${v}${decoration}`;
  });

  return result;
}

// 지난 시간으로 변환
function timeFormat(value) {
  const date = new Date(value);

  const temp = new Date().getTime() - date.getTime();

  // 1분이하
  if (temp / 1000 < 60) {
    return `${Math.floor(temp / 1000)}초전`;
  }
  // 1시간이하
  if (temp / 1000 / 60 < 60) {
    return `${Math.floor(temp / 1000 / 60)}분전`;
  }
  // 1일이하
  if (temp / 1000 / 60 / 60 < 24) {
    return `${Math.floor(temp / 1000 / 60 / 60)}시간전`;
  }
  // 1월이하
  if (temp / 1000 / 60 / 60 / 24 < 30) {
    return `${Math.floor(temp / 1000 / 60 / 60 / 24)}일전`;
  }
  // 1년이하
  if (temp / 1000 / 60 / 60 / 24 / 30 < 12) {
    return `${Math.floor(temp / 1000 / 60 / 60 / 24 / 30)}개월전`;
  }
  // 1년 이상

  return `${Math.floor(temp / 1000 / 60 / 60 / 24 / 30 / 12)}년전`;
}

// 플레이 시간 변환기
function timeConverter(duration) {
  if (+duration >= 60) {
    return `${Math.floor(duration / 60)} : ${duration % 60}`;
  }
  return `0:${duration % 60}`;
}

module.exports = {
  dateFormat,
  timeFormat,
  timeConverter,
};

// 년 포멧
function yearFormat(date, form) {
  const yearRegexp = /YY{2}/g;
  let year = null;

  // 년에 대해서 언급하지 않으면 포멧하지않음
  if (!form.match(yearRegexp)) return;

  // YYYY일 때 ( 2021 )
  if (form.match(yearRegexp).length === 2) {
    year = +String(date.getFullYear()).slice(2);
  }
  // YY일 때 ( 21 )
  else if (form.match(yearRegexp).length === 1) {
    year = date.getFullYear();
  }

  return year;
}

// 월 포멧
function monthFormat(date, form) {
  const monthRegexp = /M/g;
  let month = null;

  // 월에 대해서 언급하지 않으면 포멧하지않음
  if (!form.match(monthRegexp)) return;

  month = date.getMonth() + 1;

  // mm일 때 ( 06 )
  if (form.match(monthRegexp).length === 2 && month < 10) {
    month = `0${month}`;
  }

  return month;
}

// 일 포멧
function dayFormat(date, form) {
  const dayRegexp = /D/g;
  let day = null;

  // 일에 대해서 언급하지 않으면 포멧하지않음
  if (!form.match(dayRegexp)) return;

  day = date.getDate();

  // mm일 때 ( 06 )
  if (form.match(dayRegexp).length === 2 && day < 10) {
    day = `0${day}`;
  }

  return day;
}

// 시간 포멧
function hourFormat(date, form) {
  const hourRegexp = /h/g;
  let hour = null;

  // 시간에 대해서 언급하지 않으면 포멧하지않음
  if (!form.match(hourRegexp)) return;

  hour = date.getHours();

  // mm일 때 ( 06 )
  if (form.match(hourRegexp).length === 2 && hour < 10) {
    hour = `0${hour}`;
  }

  return hour;
}

// 분 포멧
function minuteFormat(date, form) {
  const minuteRegexp = /m/g;
  let minute = null;

  // 분에 대해서 언급하지 않으면 포멧하지않음
  if (!form.match(minuteRegexp)) return;

  minute = date.getMinutes();

  // mm일 때 ( 06 )
  if (form.match(minuteRegexp).length === 2 && minute < 10) {
    minute = `0${minute}`;
  }

  return minute;
}

// 초 포멧
function secondFormat(date, form) {
  const secondRegexp = /m/g;
  let second = null;

  // 초에 대해서 언급하지 않으면 포멧하지않음
  if (!form.match(secondRegexp)) return;

  second = date.getSeconds();

  // mm일 때 ( 06 )
  if (form.match(secondRegexp).length === 2 && second < 10) {
    second = `0${second}`;
  }

  return second;
}

3. 입력 조건 검사

  1. id: 숫자와 영어가 최소 한 글자 이상 포함 && 6자리 이상
  2. password: 숫자와 영어가 최소 한 글자 이상 포함 && 8자리 이상
  3. email: 이메일 형식에 맞아야 함
  4. phoneNumber: 숫자만 11자리
  5. year, month, day: 숫자만 4자리 or 숫자만 2자리
export function validate(key, value) {
  const regxId = /(?=.*\d)(?=.*[a-zA-ZS]).{6,}/;
  const regxPassword = /(?=.*\d)(?=.*[a-zA-ZS]).{8,}/;
  const regxEmail =
    /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
  const regxPhone = /[0-9]{11,11}/;
  const regxYear = /[0-9]{4,4}/;
  const regxMonth = /[0-9]{2,2}/;

  switch (key) {
    case "id":
      return regxId.test(value);
    case "password":
      return regxPassword.test(value);
    case "email":
      return regxEmail.test(value);
    case "phone":
      return regxPhone.test(value);
    case "year":
      return regxYear.test(value);
    case "month":
    case "day":
      return regxMonth.test(value);

    default:
      return false;
  }
}

0개의 댓글