210820 ๊ฐœ๋ฐœ๊ธฐ๋ก: ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ in ์—ฐ์‚ฐ์ž, Switch~case ๋ฌธ์—์„œ์˜ OR ์กฐ๊ฑด

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

โŒ  ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ in ์—ฐ์‚ฐ์ž : ์ž˜๋ชป ์•Œ๊ณ  ์žˆ์—ˆ๋˜ ์ 

switch(true) ๋ถ„๊ธฐ๋ฌธ์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด case ๊ตฌ๋ฌธ์— in ์—ฐ์‚ฐ์ž๋ฅผ ์ ์šฉํ–ˆ๋‹ค.

๋ฐฐ์—ด์— ์†ํ•œ ์›์†Œ๊ฐ’์„ in ์—ฐ์‚ฐ์ž ์•ž์— ๋ช…์‹œํ•˜์—ฌ, ํ•ด๋‹น ์›์†Œ๊ฐ€ ๋ฐฐ์—ด์— ์กด์žฌํ•˜๋ฉด true ๋ฅผ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด false ๋ฅผ ๋ฆฌํ„ดํ•  ๊ฒƒ์ด๋ผ ์ƒ๊ฐํ–ˆ๋‹ค. 

 

์•„๋ž˜ ์ฝ”๋“œ์—์„œ ์ ์šฉํ•œ In ์—ฐ์‚ฐ์ž๊ฐ€ ๋‹น์—ฐํžˆ ์ œ๋Œ€๋กœ ์ž‘๋™ํ•  ๊ฒƒ์ด๋ผ ์ƒ๊ฐํ–ˆ์ง€๋งŒ ๊ฒฐ๊ณผ์ ์œผ๋กœ ๋ถ„๊ธฐ๋ฅผ ํƒ€์ง€ ์•Š์•˜๋‹ค.

 

const result = []

const IE = ["I", "E"]
const SN = ["S", "N"]
const TF = ["T", "F"]
const JP = ["J", "P"]

const switchResult = (key) => { // key = "I" || "E" || "S" || "N" ... || "P"
    switch (true) {
        case key in IE:
            result[0] = key
            break
        case key in SN:
            result[1] = key
            break
        case key in TF:
            result[2] = key
            break
        case key in JP:
            result[3] = key 
            break
    }
}

 

mdn ์—์„œ ๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ์—ˆ๋‹ค. 

๋ฐ”๋กœ ๋ฐฐ์—ด์—์„œ ์ฐพ๊ณ ์ž ํ•˜๋Š” ์›์†Œ ๊ฐ’์„ ๋ช…์‹œํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค ๊ฐ’์„ ๋ช…์‹œํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

 

ํ•ด์„œ ์šฐํšŒ์ฑ…์œผ๋กœ ์•„๋ž˜์ฒ˜๋Ÿผ includes() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค. 

const switchResult = (key) => {
    switch (true) {
        case IE.includes(key):
            result[0] = key
            break
        case SN.includes(key):
            result[1] = key
            break
        case TF.includes(key):
            result[2] = key
            break
        case JP.includes(key):
            result[3] = key 
            break
    }
}

 

 

๐ŸŒฟ  switch ~ case ๋ถ„๊ธฐ๋ฌธ์—์„œ์˜ OR ์กฐ๊ฑด ์ ์šฉ ๋ฐฉ๋ฒ•

switch ๋ฌธ์—์„œ or ์—ฐ์‚ฐ์ž๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•œ ์‹ค์ˆ˜๋ฅผ ๋ฒ”ํ–‡๋‹ค. 

case ๋ฌธ์— or ์—ฐ์‚ฐ์ž๋ฅผ ๊ทธ๋Œ€๋กœ ์ ์šฉํ•  ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, 

ํ”ผ์—ฐ์‚ฐ์ž๋“ค์„ ๊ฐ๊ฐ์˜ case ์— ๋”ฐ๋กœ ์ ์šฉํ•ด์•ผ ํ•œ๋‹ค.

// wrong way
const switchResult = (key) => {
    switch (key) {
        case "I" || "E":
            result[0] = key
            break
        case "F" || "T":
            result[2] = key
            break
        case "S" || "N":
            result[1] = key
            break
        case "P" || "J":
            result[3] = key
            break
    }
}



// right way
const switchResult = (key) => {
    switch (key) {
        case "I":
        case "E":
            result[0] = key
            break
        case "F":
        case "T":
            result[2] = key
            break
        case "S":
        case "N":
            result[1] = key
            break
        case "P":
        case "J":
            result[3] = key
            break
    }
}