JS_고차 함수

개발 공부 기록·2021년 4월 2일
0

JavaScript

목록 보기
2/10
post-thumbnail

일급 객체 중 함수의 특징

  • 변수에 할당(assignment)할 수 있다.
  • 다른 함수의 인자(argument)로 전달될 수 있다.
  • 다른 함수의 결과로써 리턴될 수 있다.

1) 함수를 데이터(string, number, boolean, array, object)를 다루듯이 다룰 수 있다는 걸 의미
2) 변수에 저장할 수 있기 때문에 배열의 요소나 객체의 속성 값으로 저장하는 것도 가능

고차 함수

고차 함수 : 함수를 인자(argument)로 받거나 함수를 리턴하는 함수

다른 함수(caller)의 인자(argument)로 전달되는 함수를 콜백 함수(callback function)

  • 다른 함수를 인자로 받는 경우
  • 함수를 리턴하는 경우
  • 함수를 인자로 받고, 함수를 리턴하는 경우

내장 고차 함수

자바스크립트에는 기본적으로 내장(built-in)되어 있는 고차 함수들에서 배열 메소드들 중 일부가 고차 함수에 해당

1. 배열의 filter 메소드

배열의 요소 중 특정 조건을 만족하는 요소들만을 걸러내는(filter) 메소드

  • 걸러내는 기준이 되는 특정 조건은 함수 형태로 filter 메소드의 인자로 전달
  • filter 메소드는 인자로 전달되는 콜백 함수에 배열의 요소를 다시 전달받고 콜백 함수는 전달받은 배열의 요소를 받아 (조건에 따라) 참(true) 또는 거짓(false)을 리턴
  • 배열의 각 요소가 특정 논리(함수)에 따르면, 사실(boolean)일 때 따로 분류(filter)
// 함수 표현식
const isEven = function (num) {
  return num % 2 === 0;
};

let arr = [1, 2, 3, 4];
// let output = arr.filter(짝수);
// '짝수'를 판별하는 함수가 조건으로서 filter 메소드의 인자로 전달됩니다.
let output = arr.filter(isEven);
console.log(output); // ->> [2, 4]

const isLteFive = function (str) {
  // Lte = less then equal
  return str.length <= 5;
};

arr = ['hello', 'code', 'states', 'happy', 'hacking'];
// output = arr.filter(길이 5 이하)
// '길이 5 이하'를 판별하는 함수가 조건으로서 filter 메소드의 인자로 전달됩니다.
let output = arr.filter(isLteFive);
console.log(output); // ->> ['hello', 'code', 'happy']

MDN - filter 메소드 참고

2. 배열의 map 메소드

map() 메소드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환

  • 배열의 각 요소가 특정 논리(함수)에 의해 다른 요소로 지정(map)
const cartoons = [
  {
    id: 1,
    bookType: 'cartoon',
    title: '식객',
    subtitle: '어머니의 쌀',
    createdAt: '2003-09-09',
    genre: '요리',
    artist: '허영만',
    averageScore: 9.66,
  },
  {
    id: 2,
    // .. 이하 생략
  },
  // ... 이하 생략
]; // 만화책의 모음

const findSubtitle = function (cartoon) {
  return cartoon.subtitle;
}; // 만화책 한 권의 제목을 리턴하는 로직(함수)

const subtitles = cartoons.map(findSubtitle); // 부제의 모음

MDN - map 메소드 참고

3. 배열의 reduce 메소드

reduce() 메소드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환

arr.reduce(function(accumulator, currentValue, currentIndex, array){ 
......
},initialValue);

1) 누산기 accumulator(acc)
2) 현재 값 (cur)
3) 현재 인덱스 (idx) - optional
4) 원본 배열 (src) -optional
5) 초기 값(init) - optional

initialValue를 제공하지 않으면, reduce()는 인덱스 1부터 시작해 콜백 함수를 실행하고 첫 번째 인덱스는 건너뜀initialValue를 제공하면 인덱스 0에서 시작

reduce는 여러 데이터를 하나의 데이터로 응축(reduce)할 때 사용

배열의 각 요소를 특정 응축 방법(함수)에 따라 원하는 하나의 형태로 응축(reduction)

const cartoons = [
  {
    id: 1,
    bookType: 'cartoon',
    title: '식객',
    subtitle: '어머니의 쌀',
    createdAt: '2003-09-09',
    genre: '요리',
    artist: '허영만',
    averageScore: 9.66,
  },
  {
    id: 2,
    // .. 이하 생략
  },
  // ... 이하 생략
]; // 단행본의 모음

const scoreReducer = function (sum, cartoon) {
  return sum + cartoon.averageScore;
}; // 단행본 한 권의 평점을 누적값에 더한다.

let initialValue = 0 // 숫자의 형태로 평점을 누적한다.
const cartoonsAvgScore = cartoons.reduce(scoreReducer, initialValue) / cartoons.length; 
// 모든 책의 평점을 누적한 평균을 구한다.

reduce의 색다른 사용법

1) 배열을 문자열로

function joinName(resultStr, user) {
  resultStr = resultStr + user.name + ', ';
  return resultStr;
}

let users = [
  { name: 'Tim', age: 40 },
  { name: 'Satya', age: 30 },
  { name: 'Sundar', age: 50 }
];

users.reduce(joinName, '');

2) 배열을 객체로

function makeAddressBook(addressBook, user) {
  let firstLetter = user.name[0];

  if(firstLetter in addressBook) {
    addressBook[firstLetter].push(user);
  } else {
    addressBook[firstLetter] = [];
    addressBook[firstLetter].push(user);
  }

  return addressBook;
}

let users = [
  { name: 'Tim', age: 40 },
  { name: 'Satya', age: 30 },
  { name: 'Sundar', age: 50 }
];

users.reduce(makeAddressBook, {});

MDN - reduce 메소드 참고

profile
둔필승총(鈍筆勝聰) - 기억보다는 기록을

0개의 댓글