상세 컨텐츠

본문 제목

[Codecademy] Learn JavaScript 7. Iterators

21-22/21-22 리액트 스타터 -2

by dev otcroz 2021. 10. 11. 14:01

본문

728x90

7. Iterators

● High-order Functions

1.  Introduction

고차 함수는 다른 함수를 인수로 받아들이거나 반환값을 함수로 내보내는 함수이다.

함수에 함수를 포함함으로써 프로그래밍의 추상화 수준을 높여주는 고차 함수에 대해서 알아보자. 

 


2. Function as Data 데이터로서의 함수

자바스크립트의 함수는 다른 여느 자료형과 같은 용례를 갖는다. 함수를 변수에 할당할 수도 있고, 새로운 변수에 재할당할 수도 있다.

const announceThatIAmDoingImportantWork = () => {
    console.log("I’m doing very important work!");
};

 가독성을 해칠 정도로 긴 이름을 가진 함수가 있다고 하자. 이 함수의 동작을 반복해서 실행시킬 필요가 있어, 코드를 손상시키지 않으면서 이름을 재설정하고 싶을 때가 있다. 이때 함수 이름을 재할당하는 방법을 택할 수 있다.

const busy = announceThatIAmDoingImportantWork;
 
busy(); // This function call barely takes any space!

 변수 busy는 함수 announceThatIAmDoingImportantWork의 메모리를 참조하는 레퍼런스를 갖는다.

즉, 두 이름이 동일한 저장공간을 가리켜 busy라는 새 이름으로 기존 함수를 호출할 수 있게 되었다.

이름을 재할당하는 문장에서는 함수의 반환값을 얻으려는 것이 아니기에 괄호를 쓰지 않는다는 것을 명심하자.

 

 자바스크립트의 함수는 퍼스트 클래스 객체로, 다른 객체와 마찬가지로 속성과 메서드를 가지고 있다.

함수의 속성과 메서드는 아래 링크에서 확인할 수 있다.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

 

Instruction

1. 함수의 이름을 재할당하라.

2. 함수를 새 이름으로 호출하라.

3. name 속성을 이용해 함수의 기존 이름을 콘솔에 출력하라.

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
}

// Write your code below
let is2p2  = checkThatTwoPlusTwoEqualsFourAMillionTimes;

is2p2();

console.log(is2p2.name); // Output : checkThatTwoPlusTwoEqualsFourAMillionTimes

 


2. Function as Parameters

자바스크립트에서는 다른 자료형과 마찬가지로, 함수를 함수의 매개변수로도 사용할 수 있다.

함수를 매개변수 혹은 반환값으로 사용하는 함수를 고차 함수(higher-order function)라 하며,

이때 인수로서 전달되는 함수를 콜백 함수(callback function)라고 한다.

 

 함수를 인수로서 전달할 때에는 반환값을 사용하는 대신 함수 자체를 넘겨주므로 함수를 호출하지 않는다. (함수 이름 뒤에 괄호를 붙이지 않는다.) 

const timeFuncRuntime = funcParameter => { // 인수로 전달된 함수(콜백 함수)가 매개변수 funcParameter에 저장됨
   let t1 = Date.now(); // timeFuncRuntime 함수가 실행된 시점 기록
   funcParameter(); // funcParameter 함수 호출
   let t2 = Date.now(); // funcParameter 함수가 종료된 시점 기록
   return t2 - t1; // 콜백 함수가 동작한 시간을 반환
}
 
const addOneToOne = () => 1 + 1; // 콜백 함수
 
timeFuncRuntime(addOneToOne);

 위 예시는 고차 함수 timeFuncRuntime()를 작성한 것이다. 이 함수는 함수를 인수로 받아, 시작 시간을 t1에 저장하고, 콜백 함수를 호출해 함수의 동작이 종료된 이후의 시간을 기록한 후, 함수가 실행된 시간(종료 시간-시작 시간)을 반환한다. 이후의 코드에서 addOneOne 함수를 인수로 timeFuncRuntime()을 호출했다.

timeFuncRuntime(() => {
  for (let i = 10; i>0; i--){
    console.log(i);
  }
});

위 예시는 익명 함수도 인수가 될 수 있음을 보여준다. 익명 함수를 인수로 하여 timeFuncRuntime()을 호출했다.

 

Instruction

1. 변수 time2p2에 checkThatTwoPlusTwoEqualsFourAMillionTimes()를 이용해 호출한 timeFuncRuntime()의 반환값을 저장하라. 

 

2. 두 가지 매개변수를 갖는 고차 함수를 작성하라. 함수를 두 번 호출하고, 두 경우에서 동일한 결과를 반환한 경우 함수 호출 결과를 반환하도록 하고, 그렇지 않은 경우 문자열 'This function returned inconsistent results'을 반환하도록 한다.

 

3. addTwo()를 인수로 checkConsistentOutput()을 호출한다.

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

const addTwo = num => num + 2;

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter();
  let t2 = Date.now();
  return t2 - t1;
};

// Write your code below

const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);


const checkConsistentOutput = (func, val) => {
  let case1=func(val);
  let case2=func(val);
  if (case1===case2) {
    return case1;
  }  else {return 'This function returned inconsistent results';}
};

console.log(checkConsistentOutput(addTwo,10));

 

● Iterators

1. Introduction to Iterators

반복자에 대해서 알아보자.

우리는 보통 반복을 사용할 때 for루프를 사용하고는 한다.

하지만 여러가지 내부 배열메서드를 사용하면 더 쉽게  반복을 사용할 수 있다.

이번 단원을 통해 배워보자.

 

 

이번 단원에서 배우는 메서드들을 자세히 알아보고 싶다면 밑 사이트를 이용해서 알아보자

 

Array - JavaScript | MDN (mozilla.org)


2. The .forEach() Method

.forEach()는 배열의 각 요소들에 대하여 동일한 코드를 실행할 수 있게 도와준다.

Instruction

1. .forEach()를 사용해서 요소가 바뀌는 반복문을 작성하시오.

코드
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below

fruits.forEach(function(fruitItem){
  console.log('I want to eat a '+fruitItem);
});

3. The .map() Method

.map()메서드를 이용해서 새배열을 반환해본다.

앞에서 본 .forEach()메서드와 유사하지만 새 배열을 반환한다는 것이 특징이다.

코드
const numbers = [1, 2, 3, 4, 5]; 
 
const bigNumbers = numbers.map(number => {
  return number * 10;
});

Instruction

1. .map()을 이용해서 animals를 받을 수 있는 새 배열을 만든다.

2..map()을 이용해서 100으로 나눌 때 생기는 수들이 담긴 배열을 만들어 본다.

코드
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below
const secretMessage = animals.map(animal => animal[0]);

console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below
const smallNumbers = bigNumbers.map(num => num/100);

console.log(smallNumbers)

4. The .filter() Method

.filter() 메서드는 배열의 특정 요소들을 필터링한 후 보여줄 수 있는 메서드이다.

코드
const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door']; 
 
const shortWords = words.filter(word => {
  return word.length < 6;
});

Instruction

1. .filter()을 이용해서 250보다 작은 수들만 골라서 배열에 저장하시오.

2. .filter()을 이용해서 7글자보다 작은 문자들만 골라서 배열에 저장하시오.

코드
const randomNumbers = [375, 200, 3.14, 7, 13, 852];

// Call .filter() on randomNumbers below
const smallNumbers = randomNumbers.filter(num => {
  return num < 250;
})

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];


// Call .filter() on favoriteWords below

const longFavoriteWords = favoriteWords.filter(word => {
  return word.length > 7;
})

5. The .findIndex() Method

.findIndex()메서드는 요소의 위치를 찾아준다.

true값을 출력하는 요소의 index를 보여줄 수 있다.

코드
const jumbledNums = [123, 25, 78, 5, 9]; 
 
const lessThanTen = jumbledNums.findIndex(num => {
  return num < 10;
});

const greaterThan1000 = jumbledNums.findIndex(num => {
  return num > 1000;
});
 
console.log(greaterThan1000); // Output: -1

Instruction

1. .findIndex()메서드를 사용해서 elephant가 요소로 있는 곳의 인덱스를 찾아라.

2. .findIndex()메서드를 사용해서 's'로 시작하는 단어가 있는 곳의 인덱스를 찾아라.

코드
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(animal => {
  return animal === 'elephant';
});

const startsWithS = animals.findIndex(animal => {
  return animal[0] === 's' ? true : false;
});

6.The .reduce() Method

.reduce()메서드는 배열의 반복을 수행한 후 어떠한 기준의 방식을 통해서 값이 나오게해서 배열을 줄여준다.

코드
const numbers = [1, 2, 4, 10];
 
const summedNums = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
})
 
console.log(summedNums) // Output: 17

Instruction

1. .newSum을 만들어서 변수를 할당해준다.

2. .reduce()를 이용해서 함수표현식을 만들어서 accumulator과 currentValue의 매개변수를 넣으시오.

3. 밑 명령들을 추가하시오

  • console.log('The value of accumulator: ', accumulator);
  • console.log('The value of currentValue: ', currentValue);
  • a return statement that adds accumulator to currentValue.

4. newSum콘솔에 기록하고 그 값을 확인해라

5.  두번째 인수인 10을 .reduce()를 사용해서 추가해라

코드
const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue;
}, 10);

console.log(newSum);

7.  Iterator Documentation

위에서 배운 것들을 바탕으로 문제를 풀어보자!

Instruction

1. words.some()메서드 부분에서 누락된 오류를 찾아 고쳐보자 (6보다 작은 글자 수 찾기)

2. .filter()메서드를 이용해서 문장보다 긴 단어들을 저장해준다.

3. 모든 요소에 5글자 이상의 문자들이 있는지 코드를 완성해서 확인해보자.

코드
const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

// Something is missing in the method call below

console.log(words.some((word) => {
  return word.length < 6;
}));

// Use filter to create a new array
const interestingWords=words.filter((word)=>{
  return word.length >5;
});


// Make sure to uncomment the code below and fix the incorrect code before running it

console.log(interestingWords.every((word) => { 
  return word.length>5;
} ));

8.  Choose the Right Iterator

반복을 해주는 메서드의 종류가 매우 많다.

이 중 올바른 반복 메서드를 골라서 사용하는 방법을 연습해보자.

Instruction

1. 호출된 단어를 각 값에 대해서 수행하고 반환하는 메서드로 변경해보자

2. 두번째 호출에서 글자 수가 7글자보다 긴 단어들만 나오는 배열을 보여주는 메서드로 변경해서 보여주자.

3. method를 여러값을 받아서 단일 값을 반환해주는 메서드로 변경해서 보여주자.

4.method를 함수에서 반환값에서 새 숫자 배열을 반환해주도록 메서드를 변경해서 보여주자.

5. method를 부울값을 반환해주는 메서드로 변경해서 보여주자.

코드
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];

const nums = [1, 50, 75, 200, 350, 525, 1000];

//  Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));

// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);

// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
  return acc + currVal[0]
}, "C");

console.log(word)

// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);

// Choose a method that will return a boolean value
nums.every(num => num < 0);
// OR nums.some(num => num < 0);

Corner React Starter #2

Editor 성민, 유즈

728x90

관련글 더보기