210823 ๊ฐœ๋ฐœ๊ธฐ๋ก: javascript ๋กœ์ง ๋ณ€๊ฒฝ์œผ๋กœ ์ฝ”๋“œ ์ค„์ด๊ธฐ

2021. 8. 23. 23:37ใ†๐Ÿ“” TIL

์ด๊ฑธ ๋ฆฌํŒฉํ† ๋ง์ด๋ผ ๋ถ€๋ฅด๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ (์˜คํžˆ๋ ค ํด๋ฆฐ์ฝ”๋“œ์— ๊ฐ€๊น๋‚˜?),

๋ฐฑ์—”๋“œ ๋กœ์ง ์ฒ˜๋ฆฌ ์ฝ”๋“œ๋ฅผ ๋Œ€๋Ÿ‰์œผ๋กœ ์ค„์˜€๋‹ค.

 

 

โ˜‘๏ธ Old way

์—ฌ๊ธฐ์„œ ์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์ง„ ์ด์œ ๋Š”, MBTI ํ˜•์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฆฌํ„ดํ•˜๊ธฐ ์œ„ํ•ด "E, I", "N, S", "F, T", "P, J" ์ˆœ์„œ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ •๋ ฌํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์—ฌ๊ธฐ์„œ๋Š” ์ •๋ ฌ ๋Œ€์‹ , resultObj ๋ผ๋Š” ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด, MBTI ์ˆœ์„œ๋ฅผ ํ•˜๋“œ์ฝ”๋”ฉ ํ•˜๋Š” ํ˜•์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.


// old way
saveAnswers(resultArray) {

    let mbti = {}
    resultArray.forEach(result => {
      mbti[result] = (mbti[result] || 0) + 1
    })

    const resultObj = {
      "IE": '',
      "SN" : '',
      "TF" : '',
      "JP" : ''
    }

    const switchResult = (key) => {
      switch (true) {
        case ["I", "E"].includes(key):
          resultObj.IE = key
          break
        case ["S", "N"].includes(key):
          resultObj.SN = key
          break
        case ["T", "F"].includes(key):
          resultObj.TF = key
          break
        case ["J", "P"].includes(key):
          resultObj.JP = key
          break
      }
    }
    
    for (let key in mbti) {
      if (mbti[key] > 1) {
        switchResult(key)
      }
    }
  }

 

 

โœ…  New way

๊ฐœ์„ ๋œ ์ฝ”๋“œ์—์„œ๋Š”, MBTI ์œ ํ˜•๋ณ„ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌ๋œ ๋ฐฐ์—ด์„ ๋ฏธ๋ฆฌ ํ•˜๋“œ์ฝ”๋”ฉ ํ•ด๋’€๋‹ค. ์œ„ ๋ฐฉ๋ฒ•์˜ ๊ฐ์ฒดํ˜•์‹ ๋Œ€์‹ ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

์ด ๊ณผ์ •์—์„œ javascript ์˜ set() ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ–ˆ๋‹ค. ํ‰์†Œ ์•ˆ์“ฐ๋˜ ์ž๋ฃŒํ˜•์ด์ง€๋งŒ ํšจ๊ณผ๋Š” ๊ฐ•๋ ฅํ–ˆ๊ณ , ๋•๋ถ„์— ์ฝ”๋“œ์˜ ์–‘์„ ํ™• ์ค„์ผ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

// new way
saveAnswers(resultArray) {
    const MBTI = ["E", "I", "N", "S", "F", "T", "P", "J"]
    const countElements = (array, x) => array.filter(arr => x === arr).length
    const data = new Set(resultArray.filter(result => countElements(resultArray, result) > 1))
    let finalResult = ''
    MBTI.forEach(type => {
      if (data.has(type)) {
        finalResult += type
      }
    })
}

 

์ฒ˜์Œ old way ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ง  ํ›„, ์ฝ”๋“œ๊ฐ€ ๊ธฐ๋Šฅ์— ๋น„ํ•ด ๊ธธ๋‹ค๋Š” ๋Š๋‚Œ์ด ๊ณ„์† ๋“ค์—ˆ๋‹ค. ์š”์ฆ˜ switch(true) ๋ฐฉ์‹์— ๊ฝ‚ํ˜€ ์ž๊พธ ์‚ฌ์šฉํ•˜๋ ค๋‹ค ๋ณด๋‹ˆ ์ด๋ ‡๊ฒŒ ๋œ ๊ฒƒ ๊ฐ™๋‹ค. ์ฝ”๋“œ๋ฅผ ์ค„์ผ ๊ถ๋ฆฌ๋ฅผ ํ•˜๋ฉด์„œ set() ์„ ๋„์ž…ํ•˜์˜€๊ณ , mbti ์ˆœ์„œ๋ฅผ ์„ธํŒ…ํ•˜๊ธฐ ์œ„ํ•ด ๋ฏธ๋ฆฌ ํ•˜๋“œ์ฝ”๋”ฉ์œผ๋กœ MBTI ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด ์ฝ”๋“œ์–‘์„ ์ค„์ผ ์ˆ˜ ์žˆ์—ˆ๋‹ค.