[프로그래머스] 방금그곡 (reduce로 변경할 요소들 각각 지정하기 & 날짜차 구하는 방법)

쿼카쿼카·2023년 4월 16일
0

알고리즘

목록 보기
56/67

문제



코드

function solution(m, musicinfos) {
  // let ans = [0, ''];
  
  // const changeMSet = new Set(m.match(/[A-Z]#/g));
  // changeMSet.forEach(word => {
  //     const regex = new RegExp(`${word}`, 'g');
  //     m = m.replace(regex, word[0].toLowerCase());
  // })
  
  m = m.replace(/[A-Z]#/g, w => w[0].toLowerCase());
  
  // sort가 아주 조~~~~금 느림
  // musicinfos.sort((a, b) => {
  //     const [aStart, aEnd] = a.split(','), [bStart, bEnd] = b.split(',');
  //     const aTime = (new Date(`2023 ${aEnd}`) - new Date(`2023 ${aStart}`)) / 60000;
  //     const bTime = (new Date(`2023 ${bEnd}`) - new Date(`2023 ${bStart}`)) / 60000;
  //     return bTime - aTime;
  // })
          
  for(let info of musicinfos) {
      let [start, end, title, melody] = info.split(',');
      const playTime = (new Date(`2023 ${end}`) - new Date(`2023 ${start}`)) / 60000;
      
      // const changeSet = new Set(melody.match(/[A-Z]#/g))
      // changeSet.forEach(word => {
      //     const regex = new RegExp(`${word}`, 'g');
      //     melody = melody.replace(regex, word[0].toLowerCase());
      // })
      melody = melody.replace(/[A-Z]#/g, w => w[0].toLowerCase());
      
      const len = melody.length;

      if(playTime < melody.length) melody = melody.slice(0, playTime);
      else if(playTime > melody.length) melody = melody.repeat(Math.floor(playTime/len)) + melody.slice(0, playTime%len);
      
      // if(melody.indexOf(m)+1) return title; // sort 전용
      if(melody.indexOf(m)+1 && ans[0] < playTime) ans = [playTime, title]
  }
  
  return ans[0] ? ans[1] : '(None)';
}

reduce로 타겟 매개변수로 받아 변환

reduce(/regex/g, m => m[0])
  • 처음에는 match로 다 구하고 그 배열을 이용해 변환했어요. 아무리봐도... 복잡해보여요
  • reduce 두 번째 매개변수에 단어만 올 줄 알았는데 콜백함수 뭐야? 나 진짜 놀랬잖아 ㅎㅎㅎㅎ
  • 이렇게 편한 기능을 이제야 알다니!!!!

new Date로 시간차 계산

new Date('03:00') // invalid
new Data('2023 03:00') // 2023년 1/1 3시
new Date('3/23') // 현재 해 3/23 0시
  • 날짜를 구할 때는 시간만 적어주면 안 되고 연도나 날짜가 꼭 들어가야해요!
profile
쿼카에요

0개의 댓글