25.05.27 - se5ri/React GitHub Wiki

🀍 1μž₯ λ¦¬μ•‘νŠΈ λΉŒλ“œμ—…

πŸ“Œ 1. μ›Ή 개발의 λ³€μ²œμ‚¬

1.1 전톡적인 μ›Ή μ• ν”Œλ¦¬μΌ€μ΄μ…˜

  • JSP, Servlet, ASP, PHP λ“±μœΌλ‘œ 개발
  • λΈŒλΌμš°μ €λŠ” μ„œλ²„μ— νŽ˜μ΄μ§€ λ‹¨μœ„λ‘œ μš”μ²­μ„ 보내며 μ›Ήμ„œλ²„λŠ” μ™„μ„±λœ νŽ˜μ΄μ§€λ₯Ό(HTML) 응닡
  • ν™”λ©΄(View, UI)을 λ§Œλ“œλŠ” 역할은 λ°±μ—”λ“œμ˜ μ›Ήμ„œλ²„κ°€ λ‹΄λ‹Ή
  • μžλ°”μŠ€ν¬λ¦½νŠΈλŠ” 폼 데이터 검증 λ“±μ˜ 기본적인 κΈ°λŠ₯만 λ‹΄λ‹Ή
  • λΈŒλΌμš°μ € ν™”λ©΄μ˜ μΌλΆ€λ§Œ 갱신이 ν•„μš”ν•œ κ²½μš°μ—λ„ νŽ˜μ΄μ§€ 전체λ₯Ό μ„œλ²„μ— μš”μ²­ν•΄μ„œ λ°›μ•„μ˜€λ―€λ‘œ 맀번 λ¦¬ν”Œλž˜μ‹œκ°€ λ°œμƒν•΄μ„œ UX에 μ’‹μ§€ μ•ŠμŒ

1.2 λ©€ν‹° νŽ˜μ΄μ§€ μ• ν”Œλ¦¬μΌ€μ΄μ…˜(MPA, Multi Page Application)

  • Ajax, jQuery λ“± ν΄λΌμ΄μ–ΈνŠΈ μžλ°”μŠ€ν¬λ¦½νŠΈ API μ‚¬μš©
  • λΈŒλΌμš°μ €λŠ” μ„œλ²„μ— νŽ˜μ΄μ§€ λ‹¨μœ„λ‘œ μš”μ²­μ„ 보내며 μ›Ήμ„œλ²„λŠ” μ™„μ„±λœ νŽ˜μ΄μ§€λ₯Ό(HTML) 응닡
  • ν™”λ©΄(View, UI)을 λ§Œλ“œλŠ” 역할은 λ°±μ—”λ“œμ˜ μ›Ήμ„œλ²„κ°€ λ‹΄λ‹Ή
  • ν™”λ©΄ λ‘œλ”© ν›„ μ‚¬μš©μžμ™€ μƒν˜Έμž‘μš©μ— μ˜ν•΄μ„œ λ°œμƒν•˜λŠ” λΆ€λΆ„ 갱신은 ν”„λ‘ νŠΈμ—”λ“œμ˜ JSκ°€ λ‹΄λ‹Ή
  • λΈŒλΌμš°μ €λŠ” μ„œλ²„μ— νŽ˜μ΄μ§€ λ‹¨μœ„λ‘œ μš”μ²­μ„ λ³΄λ‚΄μ§€λ§Œ 같은 νŽ˜μ΄μ§€ λ‚΄μ—μ„œμ˜ 컨텐츠 갱신은 Ajaxλ₯Ό μ΄μš©ν•΄μ„œ μ„œλ²„λ‘œλΆ€ν„° 데이터λ₯Ό λ°›μ•„μ˜¨ ν›„ DOM API둜 ν™”λ©΄ κ°±μ‹ 
  • λΈŒλΌμš°μ € ν™”λ©΄μ˜ μΌλΆ€λ§Œ 갱신이 ν•„μš”ν•œ 경우 전체 ν™”λ©΄ λ¦¬ν”Œλž˜μ‹œκ°€ μ€„μ–΄λ“€μ–΄μ„œ UX에 μ’‹μŒ

1.3 단일 νŽ˜μ΄μ§€ μ• ν”Œλ¦¬μΌ€μ΄μ…˜(SPA, Single Page Application)

  • ν•˜λ‚˜μ˜ HTML νŽ˜μ΄μ§€μ—μ„œ μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ˜ λͺ¨λ“  ν™”λ©΄κ³Ό κΈ°λŠ₯ 제곡
  • μž₯점
    • 전체 νŽ˜μ΄μ§€λ₯Ό λ‹€μ‹œ λΆˆλŸ¬μ˜€μ§€ μ•Šκ³  ν•„μš”ν•œ λ°μ΄ν„°λ§Œ λ‘œλ”©ν•΄μ„œ λΉ λ₯Έ ν™”λ©΄ μ „ν™˜
    • κΉœλΉ‘μž„ μ—†λŠ” ν™”λ©΄ μ „ν™˜, μ•± 같은 UX κ΅¬ν˜„
    • μ„œλ²„ 뢀담이 κ°μ†Œλ˜λ©° ν΄λΌμ΄μ–ΈνŠΈ μ€‘μ‹¬μœΌλ‘œ 개발 κ°€λŠ₯
  • 단점
    • λͺ¨λ“  κΈ°λŠ₯을 ν•œ νŽ˜μ΄μ§€μ—μ„œ λ‹€ κ΅¬ν˜„ν•˜λ‹€ λ³΄λ‹ˆ μƒνƒœ(데이터, λ³€μˆ˜) 관리가 어렀움
    • μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œ HTML μ½”λ“œλ₯Ό 생성해야 ν•˜λ―€λ‘œ 개발 생산성 μ €ν•˜
    • λΈŒλΌμš°μ €μ˜ DOM을 자주 κ°±μ‹ ν•˜λ‹€λ³΄λ©΄ μ„±λŠ₯ μ €ν•˜ λ°œμƒ
  • Angular, React, Vue.js 등이 λŒ€ν‘œμ μœΌλ‘œ SPA κ°œλ°œμ„ μ§€μ›ν•˜λŠ” ν”„λ ˆμž„μ›Œν¬, 라이브러리
  • React의 νŠΉμ§•
    • λ‚΄μž₯된 μƒνƒœ 관리 κΈ°λŠ₯κ³Ό μ„œλ“œνŒŒν‹° λΌμ΄λΈŒλŸ¬λ¦¬κ°€ 많음
    • JSXλ₯Ό μ΄μš©ν•΄μ„œ HTML 생산성이 λ†’μŒ
    • 가상 DOM을 μ΄μš©ν•΄μ„œ μ„±λŠ₯ μ €ν•˜ μ΅œμ†Œ

πŸ“Œ 2. λ¦¬μ•‘νŠΈ κ°œλ°œμ— 자주 μ‚¬μš©ν•˜λŠ” μžλ°”μŠ€ν¬λ¦½νŠΈ 문법

2.1 ν™”μ‚΄ν‘œ ν•¨μˆ˜ (Arrow Function)

  • ν•¨μˆ˜ ν‘œν˜„μ‹μ˜ λŒ€μ•ˆμœΌλ‘œ κ°„κ²°ν•˜κ²Œ ν•¨μˆ˜ μ •μ˜
  • 읡λͺ… ν•¨μˆ˜λ‘œλ§Œ μ •μ˜ κ°€λŠ₯
  • μ‹€ν–‰ν•  μ½”λ“œκ°€ ν•˜λ‚˜λ§Œ μžˆλ‹€λ©΄ ν•¨μˆ˜ 본문의 μ€‘κ΄„ν˜Έ μƒλž΅ κ°€λŠ₯
  • ν•¨μˆ˜ 본문의 μ€‘κ΄„ν˜Έκ°€ μƒλž΅λ  경우 ν•¨μˆ˜μ˜ μ½”λ“œκ°€ μžλ™μœΌλ‘œ λ¦¬ν„΄κ°’μœΌλ‘œ μ‚¬μš©λ¨
  • 맀개 λ³€μˆ˜κ°€ ν•˜λ‚˜λ§Œ μžˆλ‹€λ©΄ λ§€κ°œλ³€μˆ˜μ˜ κ΄„ν˜Έ μƒλž΅ κ°€λŠ₯

μ˜ˆμ‹œ

  • λ§€κ°œλ³€μˆ˜κ°€ μ—†λŠ” ν•¨μˆ˜
// κΈ°μ‘΄ ν•¨μˆ˜
const add = function(x, y) {
  return x + y;
};
// ν™”μ‚΄ν‘œ ν•¨μˆ˜
const add = (x, y) => {
  return x + y;
}
// ν™”μ‚΄ν‘œ ν•¨μˆ˜ 본문의 μ€‘κ΄„ν˜Έ μƒλž΅
const add = (x, y) => x + y;
  • λ§€κ°œλ³€μˆ˜κ°€ μžˆλŠ” ν•¨μˆ˜
// κΈ°μ‘΄ ν•¨μˆ˜
const add10 = function(x) {
  return x + 10;
};
// ν™”μ‚΄ν‘œ ν•¨μˆ˜
const add10 = (x) => {
  return x + 10;
}
// ν™”μ‚΄ν‘œ ν•¨μˆ˜ λ§€κ°œλ³€μˆ˜μ˜ κ΄„ν˜Έμ™€ 본문의 μ€‘κ΄„ν˜Έ μƒλž΅
const add10 = x => x + 10;

2.2 ꡬ쑰 λΆ„ν•΄ ν• λ‹Ή (Destructuring assignment)

  • λ°°μ—΄μ΄λ‚˜ 객체의 속성을 ν•΄μ²΄ν•˜μ—¬ κ·Έ 값을 κ°œλ³„ λ³€μˆ˜μ— 담을 수 μžˆλŠ” ν‘œν˜„μ‹

μ˜ˆμ‹œ

  • λ°°μ—΄ ꡬ쑰 λΆ„ν•΄
const foo = ['yellow', 'green', 'blue'];
const [one, two, three] = foo;
console.log(one, two, three); // yellow green blue
  • 객체 ꡬ쑰 λΆ„ν•΄
const kim = { userName: 'ꡬ뢄핑', userAge: 35 };
const { userName, userAge: age } = kim;
console.log(userName, age); // ꡬ뢄핑 35

2.3 λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜ (Rest parameters)

  • μ •ν•΄μ§€μ§€ μ•Šμ€ 수의 λ§€κ°œλ³€μˆ˜λ₯Ό λ°°μ—΄λ‘œ 전달 λ°›μŒ
  • ν•¨μˆ˜μ˜ λ§ˆμ§€λ§‰ λ§€κ°œλ³€μˆ˜ μ•žμ— ... 을 λΆ™μž„

μ˜ˆμ‹œ

function fn(a, b, ...args) {
  console.log(a, b, args);
}

fn(); // undefined undefined []
fn(1); // 1 undefined []
fn(2, 3); // 2 3 []
fn(4, 5, 6); // 4 5 [6]
fn(7, 8, 9, 10, 11); // 7 8 [9, 10, 11]

2.4 μ „κ°œ ꡬ문 (Spread syntax)

  • λ°°μ—΄μ΄λ‚˜ 객체의 μš”μ†Œ, 속성을 λΆ„ν•΄ν•΄μ„œ λ°°μ—΄, 객체, ν•¨μˆ˜μ— 전달
  • λ°°μ—΄, 객체의 λ¦¬ν„°λŸ΄μ΄λ‚˜ ν•¨μˆ˜μ˜ μΈμžκ°’ λ³€μˆ˜ μ•žμ— ... 을 λΆ™μž„
  • λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜λŠ” μ—¬λŸ¬ λ§€κ°œλ³€μˆ˜λ₯Ό ν•˜λ‚˜μ˜ λ°°μ—΄λ‘œ λͺ¨μ•„μ„œ 처리 ν•˜λŠ” 반면 μ „κ°œ μ—°μ‚°μžλŠ” ν•˜λ‚˜μ˜ λ°°μ—΄, 객체λ₯Ό μ—¬λŸ¬κ°œμ˜ μš”μ†Œ, μ†μ„±μœΌλ‘œ λΆ„ν•΄ν•΄μ„œ 전달
  • μ΄ν„°λŸ¬λΈ” 객체(λ°°μ—΄, 객체 λ“±)λ₯Ό μ†μ‰½κ²Œ 볡사

μ˜ˆμ‹œ

const state = [ 'orange', 'yellow', 'green' ];
const newState = [ ...state ]; // λ³΅μ‚¬λœ λ°°μ—΄ ['orange', 'yellow', 'green']
const state = { name: '전ꡬ핑', age: 30 };
const newState = { ...state }; // λ³΅μ‚¬λœ 객체 { name: '전ꡬ핑', age: 30 }
function sum(x, y) {
  return x + y;
}
const numbers = [ 1, 2 ];
console.log(sum(...numbers)); // 3
//μ „κ°œκ΅¬λ¬Έμ„ μ“°μ§€ μ•Šμ„ 경우: sum(number[0] + number[1])

2.5 μ‚Όν•­ μ—°μ‚°μž (쑰건뢀 μ—°μ‚°μž)

  • 쑰건에 따라 값을 μ„ νƒν•˜λŠ” μ—°μ‚°μž
  • 쑰건 ? 참일 λ•Œμ˜ κ°’ : 거짓일 λ•Œμ˜ κ°’

μ˜ˆμ‹œ

var num = 10;
var result = num % 2 === 0 ? '짝수' : 'ν™€μˆ˜'; (True / False)
console.log(result);  // '짝수'
var num = 15;
var result = num % 2 === 0 ? '짝수' : 'ν™€μˆ˜';
console.log(result);  // 'ν™€μˆ˜'

2.6 ESM (ECMAScript Modules)

  • μ½”λ“œλ₯Ό 파일 λ‹¨μœ„λ‘œ λΆ„λ¦¬ν•˜κ³ , λΆˆν•„μš”ν•œ μ „μ—­ μ˜€μ—Ό 없이 μž¬μ‚¬μš©ν•  수 있게 ν•΄μ€Œ
  • 파일 μžμ²΄κ°€ λ…λ¦½λœ μŠ€μ½”ν”„λ₯Ό κ°€μ§€λ―€λ‘œ λͺ¨λ“ˆλ‚΄μ—μ„œ μ„ μ–Έν•œ λ³€μˆ˜λŠ” μ „μ—­λ³€μˆ˜κ°€ μ•„λ‹Œ λͺ¨λ“ˆλ³€μˆ˜λ‘œμ¨ λͺ¨λ“ˆ λ‚΄λΆ€μ—μ„œλ§Œ μ ‘κ·Ό κ°€λŠ₯
  • λͺ¨λ“ˆ ꡬ성 μš”μ†Œ(λ³€μˆ˜, ν•¨μˆ˜, 클래슀, νƒ€μž… 별칭, μΈν„°νŽ˜μ΄μŠ€ λ“±)λ₯Ό λͺ…μ‹œμ μœΌλ‘œ 내보내기(export) ν•˜λ©΄ λ‹€λ₯Έ λͺ¨λ“ˆμ—μ„œ μ‚¬μš© κ°€λŠ₯
  • λ‹€λ₯Έ λͺ¨λ“ˆμ—μ„œ exportν•œ 값을 μ°Έμ‘°ν•˜λ €λ©΄ import ꡬ문을 μ‚¬μš©
  • λΈŒλΌμš°μ €μ—μ„œ λͺ¨λ“ˆμ„ μ‚¬μš©ν•˜λ €λ©΄ <script> νƒœκ·Έμ— type="module" 속성을 μΆ”κ°€

2.6.1 export ν‚€μ›Œλ“œ

  • λͺ¨λ“ˆ ꡬ성 μš”μ†Œ(λ³€μˆ˜, ν•¨μˆ˜, 클래슀, νƒ€μž… 별칭, μΈν„°νŽ˜μ΄μŠ€ λ“±)λ₯Ό μ™ΈλΆ€λ‘œ 내보내 λ‹€λ₯Έ λͺ¨λ“ˆμ—μ„œ μ‚¬μš©ν•  수 있게 ν•΄μ£ΌλŠ” ν‚€μ›Œλ“œ

Named Export

  • 내보내기할 각 ꡬ성 μš”μ†Œ μ•žμ— export ν‚€μ›Œλ“œλ₯Ό μ§€μ •ν•˜κ±°λ‚˜ export { plus, minus } ν˜•νƒœλ‘œ μ„ μ–Έκ³Ό λΆ„λ¦¬ν•΄μ„œ λ”°λ‘œ μž‘μ„± κ°€λŠ₯
  • exportλŠ” μ—¬λŸ¬λ²ˆ μ‚¬μš© κ°€λŠ₯
  • importμ‹œ μ€‘κ΄„ν˜Έ μ•ˆμ— μ •ν™•ν•œ ꡬ성 μš”μ†Œλͺ…을 μ‚¬μš©

Default Export

  • 내보내기할 ꡬ성 μš”μ†Œ μ•žμ— export default ν‚€μ›Œλ“œ μ§€μ •
  • export defaultλŠ” λͺ¨λ“ˆ λ‚΄μ—μ„œ ν•œλ²ˆλ§Œ μ‚¬μš© κ°€λŠ₯
  • importμ‹œ 이름은 자유둭게 μ§€μ • κ°€λŠ₯

2.6.2 import ν‚€μ›Œλ“œ

  • λ‹€λ₯Έ λͺ¨λ“ˆμ—μ„œ exportν•œ ꡬ성 μš”μ†Œλ₯Ό κ°€μ Έμ˜¬ λ•Œ μ‚¬μš©ν•˜λŠ” ν‚€μ›Œλ“œ

Named Import

  • export둜 내보낸 ꡬ성 μš”μ†Œλ₯Ό μ€‘κ΄„ν˜Έλ‘œ κ°μ‹Έμ„œ κ°€μ Έμ˜΄
  • 이름이 μ •ν™•νžˆ 일치 ν•΄μ•Ό ν•˜λ©° ν•„μš”ν•œ κ²ƒλ§Œ μ„ νƒν•΄μ„œ import κ°€λŠ₯
  • 별칭 μ‚¬μš© κ°€λŠ₯

Default Import

  • export default둜 내보낸 ꡬ성 μš”μ†ŒλŠ” μ€‘κ΄„ν˜Έ 없이 자유둭게 이름을 μ§€μ •ν•΄μ„œ import κ°€λŠ₯

Mixed Import

  • Named Import와 Default Importλ₯Ό 같이 μ‚¬μš© (일관성과 가독성 μ €ν•˜λ‘œ ꢌμž₯ν•˜μ§€ μ•ŠμŒ)

Type Import

  • νƒ€μž… λ³„μΉ­μ΄λ‚˜ μΈν„°νŽ˜μ΄μŠ€λ₯Ό export ν–ˆμ„ 경우 import μ‹œ type ν‚€μ›Œλ“œ μΆ”κ°€ (μƒλž΅ κ°€λŠ₯)

2.6.3 μ˜ˆμ‹œ

  • math.ts
// Named Export
export function plus(a: number, b: number) {
  return a + b;
}

// Named Export
export function minus(a: number, b: number) {
  return a - b;
}

// Default Export
export default { plus, minus }
  • index.ts
// Named Import
import { plus as add, minus } from './math.js';
// Default Import
import MyMath from './math.js'; // { plus, minus }
add(2, 3);
minus(2, 3);
MyMath.plus(2, 3);
MyMath.minus(2, 3);
  • index.html
<script type="module" src="index.js"></script>

2.7 Promise

  • 비동기 μž‘μ—…μ˜ 성곡 λ˜λŠ” μ‹€νŒ¨ κ²°κ³Όλ₯Ό λ‚˜μ€‘μ— μ „λ‹¬ν•˜κΈ° μœ„ν•œ 객체(ES2015에 μΆ”κ°€)
  • μ–΄λ–€ ν•¨μˆ˜κ°€ Promise 객체λ₯Ό λ°˜ν™˜ν•œλ‹€λ©΄ ν˜„μž¬ μž‘μ—…μ„ 처리 쀑이며 μž‘μ—…μ΄ 처리 μ™„λ£Œλ˜λŠ” λ―Έλž˜μ— μ–΄λ–€ 값을 μ€€λΉ„ν•΄μ„œ 전달할 κ²ƒμ΄λΌλŠ” 약속

2.7.1 Promise μƒμ„±μž ν•¨μˆ˜

  • Promise 객체 생성에 μ‚¬μš©
  • executor: λΉ„λ™κΈ°λ‘œ μ²˜λ¦¬ν•  μž‘μ—…μ„ κ°€μ§„ ν•¨μˆ˜
  • resolve: μž‘μ—…μ΄ μ„±κ³΅μ μœΌλ‘œ μ™„λ£Œ λ˜μ—ˆμ„ λ•Œ ν˜ΈμΆœν•  ν•¨μˆ˜. μΈμžκ°’μ€ μž‘μ—… κ²°κ³Όλ₯Ό μ „λ‹¬ν•˜λŠ”λ° μ‚¬μš©
  • reject: μž‘μ—…μ΄ μ‹€νŒ¨ ν–ˆμ„ λ•Œ ν˜ΈμΆœν•  ν•¨μˆ˜. μΈμžκ°’μ€ μ‹€νŒ¨ μ‚¬μœ λ₯Ό μ „λ‹¬ν•˜λŠ”λ° μ‚¬μš©
new Promise<T>(
  executor: (
    resolve: (value: T) => void,
    reject: (reason?: any) => void
  ) => void
)

2.7.2 Promise 객체 λ°˜ν™˜

  • Promise 객체λ₯Ό λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜λŠ” 비동기 ν•¨μˆ˜κ°€ 됨

2.7.3 Promise μƒμ„±μž ν•¨μˆ˜μ˜ executor ν•¨μˆ˜ μž‘μ„±

  • executor ν•¨μˆ˜μ—μ„œ μ²˜λ¦¬ν•  μž‘μ—… κ΅¬ν˜„
  • μž‘μ—… 성곡 μ‹œ resolve()λ₯Ό ν˜ΈμΆœν•˜κ³  μΈμžκ°’μœΌλ‘œ μž‘μ—… κ²°κ³Ό 전달
  • μž‘μ—… μ‹€νŒ¨ μ‹œ reject()λ₯Ό ν˜ΈμΆœν•˜κ³  μΈμžκ°’μœΌλ‘œ μ‹€νŒ¨ μ‚¬μœ  전달
function f1(){
  return new Promise<string>((resolve, reject) => {
    const delay = Math.random()*1000*10;
    setTimeout(() => {
      console.log('f1 μž‘μ—… μ™„λ£Œ.', delay);
      if(delay < 5000) {
        resolve('f1의 μž‘μ—… κ²°κ³Ό.');
      }else{
        reject('f1 μž‘μ—…μ€‘ μ—λŸ¬ λ°œμƒ.');
      }
    }, delay);
  });
}

2.7.4 Promise 객체의 λ©”μ„œλ“œ

  • then(onfulfilled?: value => (void | Promise), onrejected?: reason => (void | Promise)): Promise

    • onfulfilled: resolve()κ°€ 호좜될 λ•Œ μ‹€ν–‰λ˜λŠ” ν•¨μˆ˜
    • value: 비동기 ν•¨μˆ˜μ—μ„œ μž‘μ—… 성곡 μ‹œ ν˜ΈμΆœν•œ resolve()에 μ „λ‹¬ν•œ μΈμžκ°’
    • onrejected: reject()κ°€ 호좜될 λ•Œ μ‹€ν–‰λ˜λŠ” ν•¨μˆ˜
    • reason: 비동기 ν•¨μˆ˜μ—μ„œ μž‘μ—… μ‹€νŒ¨ μ‹œ ν˜ΈμΆœν•œ reject()에 μ „λ‹¬ν•œ μΈμžκ°’
    • 리턴값: μƒˆλ‘œμš΄ Promiseκ°€ λ°˜ν™˜λ˜μ–΄ 체인 λ°©μ‹μœΌλ‘œ 호좜이 κ°€λŠ₯
    • onfulfilledλ‚˜ onrejected κ°€ Promiseλ₯Ό λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜μΌ 경우 μ—¬λŸ¬ 비동기 ν•¨μˆ˜λ₯Ό 순차적으둜 ν˜ΈμΆœν•˜λŠ”λ° μ‚¬μš©
    function test(){
      f1().then((result) => {
        console.log('f1의 μž‘μ—…μ΄ μ™„λ£Œλœ ν›„ 호좜.', result);
      }, (reason) => {
        console.error('f1의 μž‘μ—…μ΄ μ‹€νŒ¨ν•œ ν›„ 호좜.', reason);
      }).then(()=>{}).then(()=>{}).then(()=>{}); // μ²΄μΈλ°©μ‹μœΌλ‘œ 이어져 μ“°λŠ” 게 κ°€λŠ₯
    }
  • catch(onrejected?: reason => (void | Promise)): Promise

    • onrejected: then()의 onrejected와 동일
    • then()의 λ‘λ²ˆμ§Έ 인자인 onrejectedμ—μ„œ μ²˜λ¦¬ν•˜μ§€ μ•Šμ€ μ—λŸ¬λŠ” catch()μ—μ„œ 처리됨
  • finally(onfinally?: () => void): Promise

    • onfinally: Promise의 성곡 μ‹€νŒ¨μ™€ 상관없이 항상 ν˜ΈμΆœλ˜λŠ” ν•¨μˆ˜
    function test(){
      f1().then((result) => {
        console.log('4. 첫번째 f1의 μž‘μ—…μ΄ μ™„λ£Œλœ ν›„ 호좜.', result);
      }).then(f1).then((result) => {
        console.log('5. λ‘λ²ˆμ§Έ f1의 μž‘μ—…μ΄ μ™„λ£Œλœ ν›„ 호좜.', result);
      }).catch((reason) => {
        console.error('f1의 μž‘μ—…μ΄ μ‹€νŒ¨ν•œ ν›„ 호좜.', reason);
      }).finally(() => {
        console.log('f1의 성곡, μ‹€νŒ¨μ™€ 상관없이 항상 호좜.');
      });
    }

2.8 async/await

  • Promiseλ₯Ό μ‰½κ²Œ 닀루기 μœ„ν•΄ ES2017에 μΆ”κ°€λœ 문법
  • μ½œλ°±ν—¬μ΄λ‚˜ then()의 λ³΅μž‘ν•œ 체인 방식을 μ‚¬μš©ν•˜μ§€ μ•Šκ³ λ„ 비동기 ν•¨μˆ˜μ˜ 순차적인 호좜이 κ°€λŠ₯ν•΄μ„œ 비동기 μ½”λ“œλ₯Ό 마치 동기 μ½”λ“œμ²˜λŸΌ μž‘μ„±ν•  수 있음

2.8.1 async ν‚€μ›Œλ“œ

  • ν•¨μˆ˜ 선언뢀에 λΆ™μ΄λŠ” ν‚€μ›Œλ“œ
  • async ν‚€μ›Œλ“œκ°€ 뢙은 ν•¨μˆ˜λŠ” μžλ™μœΌλ‘œ Promise 객체λ₯Ό λ°˜ν™˜
  • async ν•¨μˆ˜κ°€ λ¦¬ν„΄ν•œ 값은 Promise의 resolve()에 값을 μ „λ‹¬ν•˜λŠ” 효과
  • async ν•¨μˆ˜κ°€ throwν•œ 값은 Promise의 reject()에 값을 μ „λ‹¬ν•˜λŠ” 효과
function p1(){ // Promise
  return new Promise((resolve) => {
    resolve('p1 κ²°κ³Ό');
  });
}
async function a1(){ // async
  return 'a1 κ²°κ³Ό';
}

2.8.2 await ν‚€μ›Œλ“œ

  • Promise 객체 μ•žμ— λΆ™μ—¬μ„œ, Promiseκ°€ 처리될 λ•ŒκΉŒμ§€(settled) κΈ°λ‹€λ Έλ‹€κ°€, κ·Έ 결과값을 λ°˜ν™˜ν•΄μ£ΌλŠ” ν‚€μ›Œλ“œ
  • async ν•¨μˆ˜ μ•ˆμ—μ„œλ§Œ μ‚¬μš© κ°€λŠ₯
  • μ½”λ“œμ˜ 흐름이 λ™κΈ°ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•˜λŠ” 것과 λΉ„μŠ·ν•΄μ„œ 가독성이 쒋아짐
function test(){
  p1().then(result => {
    console.log('p1의 μž‘μ—… κ²°κ³Ό.', result);
  }).then(a1).then(result => {
    console.log('a1의 μž‘μ—… κ²°κ³Ό.', result);
  }).then(p2).then(result => {
    console.log('p2의 μž‘μ—… κ²°κ³Ό.', result);
  }).then(a2).then(result => {
    console.log('a2의 μž‘μ—… κ²°κ³Ό.', result);
  }).catch(error => {
    console.log('μ—λŸ¬ λ°œμƒ.', error);
  });
}
async function test(){
  try {
    const result1 = await p1();
    console.log('p1의 μž‘μ—… κ²°κ³Ό.', result1);
    const result2 = await a1();
    console.log('a1의 μž‘μ—… κ²°κ³Ό.', result2);
    const result3 = await p2();
    console.log('p2의 μž‘μ—… κ²°κ³Ό.', result3);
    const result4 = await a2();
    console.log('a2의 μž‘μ—… κ²°κ³Ό.', result4);
  } catch(error) {
    console.log('μ—λŸ¬ λ°œμƒ.', error);
  }
}

2.9 λ°°μ—΄ λ©”μ„œλ“œ

2.9.1 push, pop

  • push(...items): number
    • λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μœ„μΉ˜μ— items μš”μ†Œλ“€μ„ μΆ”κ°€ν•˜κ³  μƒˆλ‘œμš΄ λ°°μ—΄ 길이λ₯Ό λ°˜ν™˜
  • pop(): any | undefined
    • λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μš”μ†Œλ₯Ό μ œκ±°ν•˜κ³  λ°˜ν™˜

μ˜ˆμ‹œ

const fruits = ['사과', 'λ°”λ‚˜λ‚˜'];

const newLength = fruits.push('μ˜€λ Œμ§€');
console.log(newLength, fruits);    // 3 ['사과', 'λ°”λ‚˜λ‚˜', 'μ˜€λ Œμ§€']

fruits.push('λ”ΈκΈ°', '포도');
console.log(fruits);    // ['사과', 'λ°”λ‚˜λ‚˜', 'μ˜€λ Œμ§€', 'λ”ΈκΈ°', '포도']

let lastFruit = fruits.pop();
console.log(lastFruit, fruits);   // 포도 ['사과', 'λ°”λ‚˜λ‚˜', 'μ˜€λ Œμ§€', 'λ”ΈκΈ°']

lastFruit = fruits.pop();
console.log(lastFruit, fruits);   // λ”ΈκΈ° ['사과', 'λ°”λ‚˜λ‚˜', 'μ˜€λ Œμ§€']

2.9.2 unshife, shift

  • unshift(...items): number
    • λ°°μ—΄μ˜ λ§¨μ•žμ— items μš”μ†Œλ“€μ„ μ‚½μž…ν•˜κ³  μƒˆλ‘œμš΄ λ°°μ—΄ 길이λ₯Ό λ°˜ν™˜
  • shift(): any | undefined
    • λ°°μ—΄μ˜ 첫 번째 μš”μ†Œλ₯Ό μ œκ±°ν•˜κ³  λ°˜ν™˜

μ˜ˆμ‹œ

const fruits = ['사과', 'λ°”λ‚˜λ‚˜'];

const newLength = fruits.unshift('λ”ΈκΈ°');
console.log(newLength, fruits); // 3 ['λ”ΈκΈ°', '사과', 'λ°”λ‚˜λ‚˜']

fruits.unshift('λ”ΈκΈ°', '포도');
console.log(fruits); // ['λ”ΈκΈ°', '포도', 'λ”ΈκΈ°', '사과', 'λ°”λ‚˜λ‚˜']

let firstFruit = fruits.shift();
console.log(firstFruit, fruits); // λ”ΈκΈ° ['포도', 'λ”ΈκΈ°', '사과', 'λ°”λ‚˜λ‚˜']

firstFruit = fruits.shift();
console.log(firstFruit,  fruits); // 포도 ['λ”ΈκΈ°', '사과', 'λ°”λ‚˜λ‚˜']

2.9.3 indexOf, lastIndexOf

  • indexOf(searchElement, fromIndex?: number): number
    • λ°°μ—΄μ˜ μš”μ†Œ 쀑 searchElement와 μΌμΉ˜ν•˜λŠ” 첫 번째 μš”μ†Œμ˜ 인덱슀λ₯Ό λ°˜ν™˜. μΌμΉ˜ν•˜λŠ” μš”μ†Œκ°€ μ—†μœΌλ©΄ -1 λ°˜ν™˜
    • fromIndex에 μ§€μ •ν•œ μΈλ±μŠ€λΆ€ν„° 탐색을 μ‹œμž‘ (κΈ°λ³Έκ°’ 0)
  • lastIndexOf(searchElement, fromIndex?: number): number
    • λ°°μ—΄μ˜ μš”μ†Œ 쀑 searchElement와 μΌμΉ˜ν•˜λŠ” λ§ˆμ§€λ§‰ μš”μ†Œμ˜ 인덱슀λ₯Ό λ°˜ν™˜. μΌμΉ˜ν•˜λŠ” μš”μ†Œκ°€ μ—†μœΌλ©΄ -1 λ°˜ν™˜
    • fromIndex에 μ§€μ •ν•œ μΈλ±μŠ€λΆ€ν„° 탐색을 μ‹œμž‘ (κΈ°λ³Έκ°’ 0)

μ˜ˆμ‹œ

const arr = [1, 3, 5, 8, 9, 3, 4, 5];
console.log('첫번째 3의 μœ„μΉ˜', arr.indexOf(3)); // 1
console.log('λ§ˆμ§€λ§‰ 3의 μœ„μΉ˜', arr.lastIndexOf(3)); // 5

2.9.4 includes, concat

  • includes(searchElement, fromIndex?: number): boolean
    • λ°°μ—΄μ˜ μš”μ†Œ 쀑 searchElement 값이 μžˆλŠ”μ§€ μ—¬λΆ€λ₯Ό λ°˜ν™˜
    • fromIndex에 μ§€μ •ν•œ μΈλ±μŠ€λΆ€ν„° 탐색을 μ‹œμž‘ (κΈ°λ³Έκ°’ 0)
  • concat(...items)
    • items 배열듀을 λ³‘ν•©ν•œ μƒˆλ‘œμš΄ 배열을 λ°˜ν™˜

μ˜ˆμ‹œ

const arr = ['μ˜€λ Œμ§€', 'λ”ΈκΈ°', '레λͺ¬'];
console.log(arr.includes('레λͺ¬')); // true
console.log(arr.includes('사과')); // false

const arr2 = arr.concat(['사과', 'λ°”λ‚˜λ‚˜'], ['포도']);
console.log(arr2.includes('사과')); // true

console.log(arr); // [ 'μ˜€λ Œμ§€', 'λ”ΈκΈ°', '레λͺ¬' ]
console.log(arr2); // [ 'μ˜€λ Œμ§€', 'λ”ΈκΈ°', '레λͺ¬', '사과', 'λ°”λ‚˜λ‚˜', '포도' ]

2.9.5 splice

  • splice(start: number, deleteCount?: number, ...items)
    • λ°°μ—΄μ—μ„œ μš”μ†Œλ₯Ό μΆ”κ°€, 제거 λ˜λŠ” ꡐ체 ν•œλ‹€.
    • start: μ‹œμž‘ 인덱슀
    • deleteCount: μ œκ±°ν•  μš”μ†Œ 수
    • items: μ‚½μž…ν•  μš”μ†Œ λͺ©λ‘

μ˜ˆμ‹œ

const arr1 = ['ν•œλ†ˆ', '두식이', '석삼', 'λ„ˆκ΅¬λ¦¬', 'μ˜€μ§•μ–΄', '윑개μž₯', '칠뜨기'];

let arr2 = arr1.splice(1, 2); // 인덱슀 1λΆ€ν„° 2개 μΆ”μΆœ
console.log(arr1, arr2); // ['ν•œλ†ˆ','λ„ˆκ΅¬λ¦¬','μ˜€μ§•μ–΄','윑개μž₯','칠뜨기'] ['두식이','석삼']

arr2 = arr1.splice(2, 2); // 인덱슀 2λΆ€ν„° 2개 μΆ”μΆœ
console.log(arr1, arr2); // ['ν•œλ†ˆ', 'λ„ˆκ΅¬λ¦¬', '칠뜨기'] ['μ˜€μ§•μ–΄', '윑개μž₯']

arr2 = arr1.splice(2); // 인덱슀 2λΆ€ν„° λκΉŒμ§€ μΆ”μΆœ
console.log(arr1, arr2); // ['ν•œλ†ˆ', 'λ„ˆκ΅¬λ¦¬'] ['칠뜨기']

arr2 = arr1.splice(1, 1, '두식이', '석삼'); // 인덱슀 1λΆ€ν„° 1개 μΆ”μΆœν•˜κ³  두식이, 석삼 μΆ”κ°€
console.log(arr1, arr2); // ['ν•œλ†ˆ', '두식이', '석삼'] ['λ„ˆκ΅¬λ¦¬']

2.9.6 slice

  • slice(start?: number, end?: number)
    • λ°°μ—΄μ˜ μ§€μ •ν•œ λ²”μœ„λ₯Ό λ³΅μ‚¬ν•΄μ„œ μƒˆ λ°°μ—΄λ‘œ λ°˜ν™˜
    • start: μ‹œμž‘ 인덱슀 (κΈ°λ³Έκ°’ 0)
    • end: μ’…λ£Œ 인덱슀 (κΈ°λ³Έκ°’ length)

μ˜ˆμ‹œ

const arr1 = ['ν•œλ†ˆ', '두식이', '석삼', 'λ„ˆκ΅¬λ¦¬', 'μ˜€μ§•μ–΄', '윑개μž₯', '칠뜨기'];

let arr2 = arr1.slice(1, 3); // 인덱슀 1λΆ€ν„° 3 μ•žκΉŒμ§€ 볡사
console.log(arr2); // ['두식이', '석삼']

arr2 = arr1.slice(2, 2); // 인덱슀 2λΆ€ν„° 2 μ•žκΉŒμ§€ 볡사
console.log(arr2); // []

arr2 = arr1.slice(5); // 인덱슀 5λΆ€ν„° λκΉŒμ§€ 볡사
console.log(arr2); // ['윑개μž₯', '칠뜨기']

arr2 = arr1.slice(-2); // 인덱슀 -2λΆ€ν„° λκΉŒμ§€ 볡사
console.log(arr2); // ['윑개μž₯', '칠뜨기']

console.log(arr1); // ['ν•œλ†ˆ', '두식이', '석삼', 'λ„ˆκ΅¬λ¦¬', 'μ˜€μ§•μ–΄', '윑개μž₯', '칠뜨기'];

2.9.7 forEach

  • forEach(callbackFn: (currentValue, index, array), thisArg?): void
    • λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ callbackFn ν•¨μˆ˜λ₯Ό μ‹€ν–‰ν•œλ‹€.
    • 콜백 ν•¨μˆ˜μ˜ currentValueμ—λŠ” λ°°μ—΄μ˜ μš”μ†Œκ°€, indexμ—λŠ” μ „λ‹¬λ˜λŠ” μš”μ†Œμ˜ μΈλ±μŠ€κ°€, arrayμ—λŠ” 원본 배열이 μ „λ‹¬λœλ‹€.
    • thisArgλŠ” 콜백 ν•¨μˆ˜μ—μ„œ this둜 μ‚¬μš©ν•  객체λ₯Ό 전달

μ˜ˆμ‹œ

const arr = [10, 20, 30];

let newArr: number[] = [];
// λ°°μ—΄μ˜ 각 μš”μ†Œλ₯Ό μˆœνšŒν•˜λ©° μ‹€ν–‰
arr.forEach((elem, i) => {
  newArr.push(elem ** 2);
});

console.log('forEach', newArr); // [100, 400, 900]

2.9.8 map

  • map(callbackfn: (currentValue, index, array), thisArg?): any[]
    • forEach와 동일
    • forEachλŠ” 리턴값이 μ—†μ§€λ§Œ map은 콜백 ν•¨μˆ˜μ—μ„œ λ¦¬ν„΄ν•œ 값을 μƒˆλ‘œμš΄ λ°°μ—΄λ‘œ λ§Œλ“€μ–΄μ„œ λ°˜ν™˜ν•œλ‹€.

μ˜ˆμ‹œ

const arr = [10, 20, 30];

// λ°°μ—΄μ˜ 각 μš”μ†Œλ₯Ό μˆœνšŒν•˜λ©° λ°˜ν™˜λ°›μ€ κ°’μœΌλ‘œ μƒˆλ‘œμš΄ λ°°μ—΄ 생성
const newArr = arr.map(function(elem, i) {
  // μš”μ†Œμ˜ μ œκ³±κ°’ λ°˜ν™˜
  return elem ** 2;
});

console.log('map', newArr); // [100, 400, 900]

2.9.9 find, findIndex, filter

  • find(callbackFn: (currentValue, index, array), thisArg?): any | undefined
    • λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ callbackFn ν•¨μˆ˜κ°€ ν˜ΈμΆœλœλ‹€.
    • trueλ₯Ό λ°˜ν™˜ν•œ 첫 콜백 ν•¨μˆ˜μ— μ „λ‹¬λœ μ—˜λ¦¬λ¨ΌνŠΈκ°€ find의 결과둜 λ°˜ν™˜λœλ‹€.
    • trueλ₯Ό λ°˜ν™˜ν•œ 콜백 ν•¨μˆ˜κ°€ 없을 경우 undefinedκ°€ λ°˜ν™˜λœλ‹€.
  • findIndex(callbackFn: (currentValue, index, array), thisArg?): number
    • λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ callbackFn ν•¨μˆ˜κ°€ ν˜ΈμΆœλœλ‹€.
    • trueλ₯Ό λ°˜ν™˜ν•œ 첫 콜백 ν•¨μˆ˜μ— μ „λ‹¬λœ μΈλ±μŠ€κ°€ find의 결과둜 λ°˜ν™˜λœλ‹€.
    • trueλ₯Ό λ°˜ν™˜ν•œ 콜백 ν•¨μˆ˜κ°€ 없을 경우 0이 λ°˜ν™˜λœλ‹€.
  • filter(callbackFn: (currentValue, index, array), thisArg?): any | undefined
    • λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ callbackFn ν•¨μˆ˜κ°€ ν˜ΈμΆœλœλ‹€.
    • trueλ₯Ό λ°˜ν™˜ν•œ 콜백 ν•¨μˆ˜μ— μ „λ‹¬λœ μš”μ†Œλ§Œ λͺ¨μ•„μ„œ μƒˆλ‘œμš΄ λ°°μ—΄λ‘œ λ°˜ν™˜
    • trueλ₯Ό λ°˜ν™˜ν•œ 콜백 ν•¨μˆ˜κ°€ 없을 경우 undefinedκ°€ λ°˜ν™˜λœλ‹€.

μ˜ˆμ‹œ

const arr = [1, 3, 5, 8, 9, 3, 4, 5];

console.log(arr.find(num => num % 2 === 0)); // 8, λ°°μ—΄μ˜ 첫번째 짝수 μ°ΎκΈ°
console.log(arr.findIndex(num => num % 2 === 0)); // 3, λ°°μ—΄μ˜ 첫번째 짝수의 인덱슀 μ°ΎκΈ°
console.log(arr.filter(n => n % 2 === 0)); // [8, 4], λ°°μ—΄μ˜ λͺ¨λ“  짝수λ₯Ό μ°ΎκΈ°

2.9.10 some, every

  • some(callbackfn: (currentValue, index, array), thisArg?): boolean
    • λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ callbackFn ν•¨μˆ˜κ°€ ν˜ΈμΆœλœλ‹€.
    • 콜백 ν•¨μˆ˜ 쀑 ν•˜λ‚˜λΌλ„ trueλ₯Ό λ°˜ν™˜ν•˜λ©΄ some은 trueλ₯Ό λ°˜ν™˜ν•œλ‹€.
    • 콜백 ν•¨μˆ˜ μ „λΆ€ trueλ₯Ό λ°˜ν™˜ν•˜μ§€ μ•ŠμœΌλ©΄ some은 falseλ₯Ό λ°˜ν™˜ν•œλ‹€.
  • every(callbackfn: (currentValue, index, array), thisArg?): boolean
    • λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ callbackFn ν•¨μˆ˜κ°€ ν˜ΈμΆœλœλ‹€.
    • 콜백 ν•¨μˆ˜ μ „λΆ€ trueλ₯Ό λ°˜ν™˜ν•˜λ©΄ everyλŠ” trueλ₯Ό λ°˜ν™˜ν•œλ‹€.
    • 콜백 ν•¨μˆ˜ 쀑 ν•˜λ‚˜λΌλ„ trueλ₯Ό λ°˜ν™˜ν•˜μ§€ μ•ŠμœΌλ©΄ everyλŠ” falseλ₯Ό λ°˜ν™˜ν•œλ‹€.

μ˜ˆμ‹œ

const arr = [1, 2, 3];

const hasEven = arr.some(n => n % 2 === 0); // true, μ§μˆ˜κ°€ ν•˜λ‚˜λ‘œλ„ μžˆλŠ”κ°€?
const isAllEven = arr.every(n => n % 2 === 0); // false, λͺ¨λ‘ μ§μˆ˜μΈκ°€?γ„΄

console.log(hasEven, isAllEven);

2.9.11 reduce

  • reduce(reducerfn: (previousValue, currentValue, index, array), initialValue?): any
    • λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ μ œκ³΅ν•œ reducerfn을 μ‹€ν–‰
    • 이전 reducerfn의 λ°˜ν™˜κ°’μ΄ λ‹€μŒ reducerfn의 μΈμžκ°’μœΌλ‘œ μ „λ‹¬λ˜λ©° μ΅œμ’…μ μœΌλ‘œ ν•˜λ‚˜μ˜ 결과값을 λ°˜ν™˜
    • reducerfn이 처음 μ‹€ν–‰λ˜λ©΄ "이전 λ¦¬λ“€μ„œμ˜ λ°˜ν™˜κ°’"이 μ—†μœΌλ―€λ‘œ reduce ν•¨μˆ˜μ˜ λ‘λ²ˆμ§Έ 인자둜 μ „λ‹¬ν•˜λŠ” initialValue 값을 μ‚¬μš©ν•˜κ±°λ‚˜ λ‘λ²ˆμ§Έ μΈμžκ°€ μƒλž΅λ  경우 λ°°μ—΄μ˜ 첫번째 index 값이 μ§€μ •λ˜κ³  λ°°μ—΄μ˜ λ‘λ²ˆμ§Έ μš”μ†ŒλΆ€ν„° λ¦¬λ“€μ„œκ°€ μ‹€ν–‰
    • ν•¨μˆ˜ν˜• μŠ€νƒ€μΌλ‘œ 개발

μ˜ˆμ‹œ

  • forEach ν•¨μˆ˜ μ‚¬μš©
const arr = [1, 2, 3, 4];

let sum = 0;
arr.forEach(function(value) {
  sum += value;
});

console.log(sum); // 0 + 1 + 2 + 3 + 4
  • reduce ν•¨μˆ˜ μ‚¬μš©
const arr = [1, 2, 3, 4];

const sum = arr.reduce(function(accumulator, currentValue){
  return accumulator + currentValue;
}, 0);

console.log(sum); // 0 + 1 + 2 + 3 + 4

2.10 λ©”λͺ¨μ΄μ œμ΄μ…˜

  • μ΄μ „μ˜ 계산 κ²°κ³Όλ₯Ό κΈ°μ–΅ν•˜λŠ” κΈ°λŠ₯을 κ°–μΆ˜ ν•¨μˆ˜
  • ν•¨μˆ˜λŠ” 객체이기 λ•Œλ¬Έμ— ν•¨μˆ˜μ˜ μ†μ„±κ°’μœΌλ‘œ 계산 κ²°κ³Ό μΊμ‹œ
  • ν•¨μˆ˜μ— μ’…μ†λœ 속성을 μ΄μš©ν•˜κΈ° λ•Œλ¬Έμ— 외뢀에 λ…ΈμΆœν•˜μ§€ μ•Šκ³  ν•¨μˆ˜ 자체적으둜 κ΅¬ν˜„ κ°€λŠ₯

2.10.1 μž₯점

  • 이미 μˆ˜ν–‰ν•œ λ³΅μž‘ν•œ 연산을 λ°˜λ³΅ν•˜μ§€ μ•Šλ„λ‘ ν•¨μœΌλ‘œμ„œ μ„±λŠ₯을 ν–₯상
  • μ‚¬μš©μžκ°€ μ•Œ 수 μ—†κ²Œ λ‚΄λΆ€μ μœΌλ‘œλ§Œ λ™μž‘

2.10.2 단점

  • μΊμ‹œμ— ν•„μš”ν•œ λ©”λͺ¨λ¦¬ μ‚¬μš©λŸ‰ 증가
  • λΉ„μ¦ˆλ‹ˆμŠ€ 둜직과 캐싱 κΈ°λŠ₯의 혼재
  • λΆ€ν•˜ ν…ŒμŠ€νŠΈ(Load test)λ‚˜ μ•Œκ³ λ¦¬μ¦˜μ˜ μ„±λŠ₯ ν…ŒμŠ€νŠΈκ°€ μ–΄λ €μ›Œμ§

2.10.3 μ˜ˆμ‹œ

  • ν•¨μˆ˜μ—μ„œ 직접 κ΅¬ν˜„
// μ§€μ •ν•œ μˆ˜κ°€ μ†Œμˆ˜μΈμ§€ μ—¬λΆ€λ₯Ό λ°˜ν™˜
const isPrime = function(num){ // num = 5
  // μΊμ‹œλ₯Ό μœ„ν•œ μ½”λ“œ
  isPrime._cache = isPrime._cache || {};
  if(isPrime._cache[num] !== undefined){ // num에 λŒ€ν•΄μ„œ 계산이 λλ‚˜κ³  μΊμ‹œλœ 경우
    return isPrime._cache[num];
  }

  // μ†Œμˆ˜ νŒλ³„ μ½”λ“œ
  let prime = true;
  for(let i=2; i<=Math.sqrt(num); i++){
    if(num % i === 0){
      prime = false;
      break;
    }
  }

  // μΊμ‹œλ₯Ό μœ„ν•œ μ½”λ“œ
  isPrime._cache[num] = prime; // isPrime._cache[5] = true;

  return prime;
};

console.time('μ†Œμš”μ‹œκ°„');
console.log('3 -> ', isPrime(3));
console.log('4 -> ', isPrime(4));
console.log('1000000007 -> ', isPrime(1000000007));
console.log('1000000007 -> ', isPrime(1000000007));
console.timeEnd('μ†Œμš”μ‹œκ°„');
  • ν΄λ‘œμ € ν™œμš©
// λͺ¨λ“  ν•¨μˆ˜μ— λ©”λͺ¨μ΄μ œμ΄μ…˜ κΈ°λŠ₯ μΆ”κ°€
Function.prototype.memo = function(key){
  this._cache = this._cache || {};
  if(this._cache[key] !== undefined){
    return this._cache[key];
  }else{
    return this._cache[key] = this(key);
  }
};
// μ§€μ •ν•œ μˆ˜κ°€ μ†Œμˆ˜μΈμ§€ μ—¬λΆ€λ₯Ό λ°˜ν™˜(순수 ν•¨μˆ˜)
const isPrime = function(num){
  // μ†Œμˆ˜ νŒλ³„ μ½”λ“œ
  let prime = true;
  for(let i=2; i<=num; i++){
    if(num % i === 0){
      prime = false;
      break;
    }
  }
  return prime;
};

console.time('μ†Œμš”μ‹œκ°„');
console.log('3 -> ', isPrime(3));
console.log('4 -> ', isPrime(4));
console.log('1000000007 -> ', isPrime.memo(1000000007));
console.log('1000000007 -> ', isPrime.memo(1000000007));
console.timeEnd('μ†Œμš”μ‹œκ°„');

TODOLIST

πŸ“œ sample

πŸ“œ 01. λͺ©λ‘μ‘°νšŒ

πŸ“œ 02. 등둝

⚠️ **GitHub.com Fallback** ⚠️