211013 ๊ฐœ๋ฐœ๊ธฐ๋ก: return ์— ์”Œ์—ฌ์ง„ ํ™”์‚ดํ‘œํ•จ์ˆ˜ (feat. ์ฝœ๋ฐฑํ•จ์ˆ˜)

2021. 10. 13. 17:15ใ†๐Ÿ“” TIL

return ๋‚ด๋ถ€์— ํ™”์‚ดํ‘œํ•จ์ˆ˜๊ฐ€ ์–ด๋–ค ์˜๋ฏธ๋กœ ์”Œ์˜€๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค๊ณ ,  ๋‹ค๋ฅธ ๊ฐœ๋ฐœ์ž๋ถ„์ด ์•„๋ž˜ ์ฝ”๋“œ์—์„œ ์งˆ๋ฌธ์„ ์ฃผ์…จ๋‹ค (๋‚ด๊ฐ€ ์ง  ์ฝ”๋“œ๋Š” ์•„๋‹ˆ๋‹ค..)

const searchData = (keyWord) => {
  return new Promise((resolve, reject) => {
    let result = dataArr.filter(this.isMatch(keyWord));
    resolve(result);
  });
};

// ๋งค์นญํ•˜๋Š” ํ•จ์ˆ˜ : ํ‚ค์›Œ๋“œ๋ฅผ ํ…์ŠคํŠธ ํ•„๋“œ์— ๋„ฃ์—ˆ์„ ๋•Œ, name | email | company ์„ธ ๊ฐœ ์ค‘์— ํ•˜๋‚˜๋ผ๋„ ์žˆ์œผ๋ฉด ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
const isMatch = (keyWord) => {
  return (value) => {
    let result =
      value["name"].indexOf(keyWord) !== -1 ||
      value["email"].indexOf(keyWord) !== -1 ||
      value["company"].indexOf(keyWord) !== -1;
    return result;
  };
};


isMatch ํ•จ์ˆ˜ ๋‚ด๋ถ€ return ์˜์—ญ์— ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๊ฐ€ ์กด์žฌํ•œ๋‹ค.
์ด๋•Œ value ๊ฐ€ ์–ด๋””์„œ ๋‚˜์˜จ ๊ฒƒ์ธ์ง€ ํ—ท๊ฐˆ๋ ธ๋Š”๋ฐ, ํ•ด๋‹น ํ•จ์ˆ˜๋Š” ์œ„์˜ searchData ํ•จ์ˆ˜์˜ filter์˜ ์ฝœ๋ฐฑํ•จ์ˆ˜์ด๋‹ค.
ํ•ด๋‹น ์ฝœ๋ฐฑํ•จ์ˆ˜๋ฅผ isMatch ๋ผ๋Š” ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋กœ ๋นผ๋‚ธ ํ˜•ํƒœ์ธ๋ฐ ์ด๋ฅผ ์ถ”์ถœ ์ „์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค.
์ฆ‰ value ๋Š” dataArr ๊ฐ์ฒด์˜ ์›์†Œ๊ฐ€ ๋œ๋‹ค.


const searchData = (keyWord) => {
  return new Promise((resolve, reject) => {
    let result = dataArr.filter((value) => {
      return (
        value["name"].indexOf(keyWord) !== -1 ||
        value["email"].indexOf(keyWord) !== -1 ||
        value["company"].indexOf(keyWord) !== -1
      );
    });
    resolve(result);
  });
};


๋งŒ์•ฝ ์œ„ ์ฒ˜๋Ÿผ return ๋ถ€๋ถ„์— ํ™”์‚ดํ‘œํ•จ์ˆ˜๊ฐ€ ์กด์žฌํ•˜๋ฉด ๋‹ค๋ฅธ ํ•จ์ˆ˜์˜ ์ฝœ๋ฐฑํ•จ์ˆ˜๊ฐ€ ์•„๋‹Œ์ง€ ์˜์‹ฌํ•ด๋ณผ ํ•„์š”๊ฐ€ ์žˆ๋‹ค.

 

 

์ถ”๊ฐ€ ) filter() ์™€ map()์˜ ์กฐํ•ฉ

filter ํ•จ์ˆ˜๋ฅผ ๊ณต๋ถ€ํ•˜๋‹ค ์•Œ๊ฒŒ๋œ  filter() ์™€ map() ์„ ์กฐํ•ฉํ•˜์—ฌ ๋‹ค์ค‘ ์กฐ๊ฑด ๋งŒ๋“ค๊ธฐ. 

const guys = [
  { name: "Kyle", salary: 500000 },
  { name: "Lim", salary: 400000 },
  { name: "Kim", salary: 300000 },
  { name: "Jacky", salary: 200000 },
];

const highSalaryMan = guys
  .filter((man) => man.salary > 300000)
  .map((man) => man.name);
console.log(highSalaryMan);

filter ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์—ฐ๋ด‰์ด 300000 ๋ณด๋‹ค ๋†’์€ ๊ฐ์ฒด๋ฅผ ์ฐพ๋Š” ๊ฒƒ์€ ์–ด๋ ต์ง€ ์•Š๋‹ค.

์—ฌ๊ธฐ์— ๋”ํ•ด, map() ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•˜๋ฉด ์—ฐ๋ด‰์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๊ฐ์ฒด์˜ ์ด๋ฆ„(name) ํ”„๋กœํผํ‹ฐ๋งŒ ๊น”๋”ํ•˜๊ฒŒ ๋ฝ‘์•„๋‚ผ ์ˆ˜ ์žˆ๋‹ค.