๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/JavaScript

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] filter + join ๋ฉ”์„œ๋“œ๋กœ ๊ฐ€๋…์„ฑ์žˆ๋Š” ์ฝ”๋“œ ์ž‘์„ฑํ•˜๊ธฐ

by YWTechIT 2022. 11. 15.
728x90

๐Ÿ“ filter + join ๋ฉ”์„œ๋“œ๋กœ ๊ฐ€๋…์„ฑ ์žˆ๋Š” ์ฝ”๋“œ ์ž‘์„ฑํ•˜๊ธฐ

string | null ํƒ€์ž…์„ ๊ฐ€์ง€๋Š” a, b๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ a·b๋กœ ๋‚˜ํƒ€๋‚ด์•ผํ•œ๋‹ค. ๋งŒ์•ฝ, ๋‘˜ ์ค‘์— ํ•˜๋‚˜๋ผ๋„ null์ผ ๊ฒฝ์šฐ ·๋ฅผ ํ‘œ์‹œํ•˜์ง€ ์•Š๊ณ , string ํƒ€์ž…๋งŒ ๋‚˜ํƒ€๋‚ด์•ผํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด a = 'foo'์ด๊ณ , b = 'bar'์ผ ๋•Œ ๋‘˜ ๋‹ค ๊ฐ’์ด ์กด์žฌํ•˜๋ฉด foo·bar๋กœ, aํƒ€์ž…๋งŒ ์กด์žฌํ•˜๋ฉด foo, bํƒ€์ž…๋งŒ ์กด์žฌํ•˜๋ฉด bar, a์™€ b ๋‘˜ ๋‹ค ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ null ํ˜น์€ ''์„ ๋‚˜ํƒ€๋‚ด์•ผํ•œ๋‹ค. ์ด๋Ÿด ๋•Œ ์–ด๋–ป๊ฒŒ ๊ฐ€๋…์„ฑ ์žˆ๊ฒŒ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ๊ฒƒ์ธ๊ฐ€?

728x90

๋ฆฌ์•กํŠธ์—์„œ ์‚ฌ์šฉํ•  ๋•Œ AS-IS๋Š” ์กฐ๊ฑด์‹๊ณผ join ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ a && b ? [a, b].join('·') : a || b๋กœ ๋‚˜ํƒ€๋ƒˆ๋Š”๋ฐ, ๊ฐ€๋…์„ฑ์ด ๋„ˆ๋ฌด ๋–จ์–ด์กŒ๋‹ค. ๊ทธ๋ž˜์„œ TO-BE ์ฒ˜๋Ÿผ filter + join ๋ฉ”์„œ๋“œ๋ฅผ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋‹ˆ ๊ฐ€๋…์„ฑ์ด ์ด์ „๋ณด๋‹ค ์ฆ๊ฐ€ํ•˜์˜€๋‹ค.

const category: string | null = '๊ฐœ๋ฐœ';
const language: string | null = 'Typescript';

// AS-IS
const result1 =
  category && language ? [category, language].join('·') : category || language

// TO-BE
const result2 = [category, language].filter(Boolean).join('·')

// category, language ๋ชจ๋‘ ๊ฐ’์ด ์žˆ๋Š”๊ฒฝ์šฐ
๐Ÿ‘‰๐Ÿพ result1: ๊ฐœ๋ฐœ·Typescript
๐Ÿ‘‰๐Ÿพ result2: ๊ฐœ๋ฐœ·Typescript

// category๋Š” ์กด์žฌํ•˜๊ณ  language๋Š” null์ธ ๊ฒฝ์šฐ
๐Ÿ‘‰๐Ÿพ result1: Typescript
๐Ÿ‘‰๐Ÿพ result2: Typescript

// category๋Š” null์ด๊ณ  language๋Š” ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ
๐Ÿ‘‰๐Ÿพ result1: ๊ฐœ๋ฐœ
๐Ÿ‘‰๐Ÿพ result2: ๊ฐœ๋ฐœ

// ๋‘˜ ๋‹ค null์ธ ๊ฒฝ์šฐ
๐Ÿ‘‰๐Ÿพ result1: null
๐Ÿ‘‰๐Ÿพ result2: ''

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€