[TIL] 211011

Lee SyongΒ·2021λ…„ 10μ›” 11일
0

TIL

λͺ©λ‘ 보기
54/204
post-thumbnail

πŸ“ 였늘 ν•œ 것

  1. HTTP / AJAX / XML / JSON / 직렬화 & 역직렬화 / 비동기 콜백 ν•¨μˆ˜ / 콜백 지μ˜₯

  2. sort() / splice() / slice() / split() / join() / find() / filter() / map() / reduce()


πŸ“– ν•™μŠ΅ 자료

  1. λ“œλ¦Όμ½”λ”© 유튜브 'μžλ°”μŠ€ν¬λ¦½νŠΈ 기초 κ°•μ˜' 9편 볡슡 / 10 ~ 11편 μˆ˜κ°•

πŸ“š 배운 것

1. λ°°μ—΄ APIs

[TIL] 210906 μ°Έκ³ 

(1) sort()

const array = [2, 4, 1, 5, 3];

/* μ˜€λ¦„μ°¨μˆœ μ •λ ¬ */
const ascending = array.sort((a, b) => a - b);
console.log(ascending); // [1, 2, 3, 4, 5]

/* λ‚΄λ¦Όμ°¨μˆœ μ •λ ¬ */
const descending = array.sort((a, b) => b - a);
console.log(descending); // [5, 4, 3, 2, 1]

(2) splice() / slice() / split() / join()

πŸ’‘ splice()

자λ₯΄κ³  (μΆ”κ°€ν•˜κΈ°) / 자λ₯Έ λ°°μ—΄ 리턴 / 원본 λ°°μ—΄ λ°”λ€œ

const array = [1, 2, 3, 4 ,5];

const array2 = array.splice(2, 2, 'πŸ™ƒ', '😭');
console.log(array2); // [3, 4]
console.log(array); // [1, 2, 'πŸ™ƒ', '😭', 5]

πŸ’‘ slice()

볡사 / λ³΅μ‚¬ν•œ λ°°μ—΄ 리턴 / 원본 λ°°μ—΄ μ•ˆ λ°”λ€œ

const array = [1, 2, 3, 4, 5];

const array2 = array.slice(1, 3);
console.log(array2); // [2, 3]
console.log(array); // [1, 2, 3, 4, 5]

πŸ’‘ string.split()

β€» λ°°μ—΄ API μ•„λ‹˜

λ¬Έμžμ—΄μ„ separator(κ΅¬λΆ„μž)λ₯Ό κΈ°μ€€μœΌλ‘œ λŠμ–΄ λ°°μ—΄λ‘œ λ§Œλ“¦
limit(λŠμ„ λ¬Έμžμ—΄μ˜ μ΅œλŒ€ 개수)λ₯Ό 지정해쀄 수 있음

// separator만 μ§€μ •ν•œ 경우
const string2 = 'What are you doing now?';
const array2 = string2.split(' ');
console.log(array2); // ['What'. 'are', 'you', 'doing', 'now?']

// limitλ₯Ό 2둜 μ§€μ •ν•œ 경우
const string = '1, 2, 3, 4, 5';
const array = string.split(', ', 2);
console.log(array); // ['1', '2']

πŸ’‘ array.join()

λ°°μ—΄μ˜ λͺ¨λ“  μš”μ†Œλ₯Ό μ—°κ²°ν•΄ 'ν•˜λ‚˜μ˜' λ¬Έμžμ—΄λ‘œ λ§Œλ“¦
λ°°μ—΄μ˜ 각 μš”μ†Œλ₯Ό ꡬ뢄할 λ¬Έμžμ—΄(separator)을 지정해쀄 수 있음

const array = ['radish', 'green orion', 'potato'];

const string = array.join();
console.log(string); // radish,green orion,potato

const string2 = array.join(' - ');
console.log(string2); // radish - green orion - potato

β€» μ•„λž˜ (3) ~ (5) 곡톡 예제

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}

const students = [  
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

(3) find()

λ°°μ—΄μ˜ μš”μ†Œλ“€ 쀑 콜백 ν•¨μˆ˜ return 값이 trueκ°€ λ˜λŠ” 첫 번째 μš”μ†Œμ˜ κ°’ λ°˜ν™˜

// μ μˆ˜κ°€ 90점인 학생 μ°ΎκΈ°
const studentWith90 = students.find((student) => student.score === 90);
console.log(studentWith90); // Student {name: 'C', age: 30, enrolled: true, score: 90}

(4) filter() / map()

πŸ’‘ filter()

λ°°μ—΄μ˜ μš”μ†Œλ“€ 쀑 콜백 ν•¨μˆ˜ return 값이 trueκ°€ λ˜λŠ” μš”μ†Œλ“€λ§Œμ„ λͺ¨μ•„ μƒˆλ‘œμš΄ 배열을 λ°˜ν™˜

// enrolled students λ°°μ—΄ λ§Œλ“€κΈ°
const enrolledStudents = students.filter((student) => student.enrolled);
console.log(enrolledStudents); // [Student, Student, Student]

πŸ’‘ map()

λ°°μ—΄ λ‚΄μ˜ λͺ¨λ“  μš”μ†Œ 각각에 λŒ€ν•˜μ—¬ 주어진 콜백 ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•œ κ²°κ³Όλ₯Ό λͺ¨μ•„(바뀐 μš”μ†Œλ“€μ„ λͺ¨μ•„) μƒˆλ‘œμš΄ 배열을 λ°˜ν™˜

// ν•™μƒλ“€μ˜ μ μˆ˜λ§Œμ„ ν¬ν•¨ν•˜λŠ” λ°°μ—΄ λ§Œλ“€κΈ°
const scores = students.map((student) => students.score);
console.log(scores); // [45, 66, 80, 88, 90]

(5) reduce()

  • 빈 μš”μ†Œλ₯Ό μ œμ™Έν•˜κ³ , λ°°μ—΄ 내에 μ‘΄μž¬ν•˜λŠ” 각 μš”μ†Œμ— λŒ€ν•΄ λ¦¬λ“€μ„œ ν•¨μˆ˜(콜백 ν•¨μˆ˜)λ₯Ό ν•œ λ²ˆμ”© 싀행함

  • κ·ΈλŸ¬λ‚˜, 콜백 ν•¨μˆ˜μ˜ return 값은 λˆ„μ‚°κΈ°(prev)에 ν• λ‹Ήλ˜κ³ , λˆ„μ‚°κΈ°λŠ” 순회 쀑 μœ μ§€λ˜λ―€λ‘œ κ²°κ΅­ λ¦¬λ“€μ„œ ν•¨μˆ˜λŠ” ν•˜λ‚˜μ˜ 값을 returnν•œλ‹€.

// 학생듀 점수의 평균값 κ΅¬ν•˜κΈ°
const scoreArray = students.map((student) => student.score);
const tatalScore = scoreArray.reduce((prev, curr) => prev + curr, 0);
const averageScore = totalScore / students.length;
cosole.log(averageScore); // 73.8
  • μœ„μ—μ„œ reduce() λ©”μ„œλ“œ μ•ˆμ— ν™”μ‚΄ν‘œ ν•¨μˆ˜λ‘œ ν‘œν˜„λ˜μ–΄ μžˆλŠ” 콜백 ν•¨μˆ˜λ₯Ό, 읡λͺ… ν•¨μˆ˜λ‘œ λ‹€μ‹œ 써보면 μ•„λž˜μ™€ κ°™λ‹€.
students.reduce(function (prev, curr) {
  return prev + curr;
}, 0);

students.reduce(function (λˆ„μ λœ 콜백 ν•¨μˆ˜ λ°˜ν™˜κ°’, μ²˜λ¦¬ν•  ν˜„μž¬ μš”μ†Œ) {
  return λˆ„μ λœ 콜백 ν•¨μˆ˜ λ°˜ν™˜κ°’ + μ²˜λ¦¬ν•  ν˜„μž¬ μš”μ†Œ;
}, μ΄ˆκΉƒκ°’);

πŸ’‘ prev

  • λˆ„μ λœ 콜백 ν•¨μˆ˜ λ°˜ν™˜κ°’ (λˆ„μ‚°κΈ° accumulator)
  • λ‹€λ§Œ, λˆ„μ λœ 값이 아직 μ—†λŠ” 콜백 ν•¨μˆ˜ 졜초 호좜 μ‹œ

μ΄ˆκΉƒκ°’ 지정 O β†’ prev = μ΄ˆκΉƒκ°’ (curr = λ°°μ—΄μ˜ 첫 번째 μš”μ†Œ)
μ΄ˆκΉƒκ°’ 지정 X β†’ prev = λ°°μ—΄μ˜ 첫 번째 μš”μ†Œ (curr = λ°°μ—΄μ˜ 두 번째 μš”μ†Œ)


2. JSON

1) HTTP(Hypertext Transfer Protocol)

  • ν΄λΌμ΄μ–ΈνŠΈκ°€ μ„œλ²„μ™€ 데이터(hypertext)λ₯Ό 주고받을 λ•Œ μ‚¬μš©λ˜λŠ” ν”„λ‘œν† μ½œ(톡신 κ·œμ•½)

  • ν•˜μ΄νΌν…μŠ€νŠΈ(hypertext)λŠ” ν•˜μ΄νΌλ§ν¬ + λ¬Έμ„œ + 이미지 파일 λ“± μ „λ°˜μ μœΌλ‘œ μ‚¬μš©λ˜λŠ” λ¦¬μ†ŒμŠ€λ“€μ„ ν¬ν•¨ν•œλ‹€.

  • ν΄λΌμ΄μ–ΈνŠΈκ°€ 데이터λ₯Ό request ν•˜λ©΄, μ„œλ²„κ°€ response ν•œλ‹€.

2) AJAX(Asyncronous JavaScript And XML)

  • μ›Ή λΈŒλΌμš°μ €κ°€ μžλ°”μŠ€ν¬λ¦½νŠΈλ₯Ό μ΄μš©ν•˜μ—¬ μ›Ή μ„œλ²„μ™€ λΉ„λ™κΈ°μ μœΌλ‘œ 데이터λ₯Ό μ£Όκ³ λ°›κ³ , DOM을 μ΄μš©ν•΄ μ›Ή νŽ˜μ΄μ§€λ₯Ό λ™μ μœΌλ‘œ κ°±μ‹ ν•˜λŠ” ν”„λ‘œκ·Έλž˜λ° 기법

  • λŒ€ν‘œμ μœΌλ‘œ XHR(XMLHttpRequest)이 μžˆλ‹€. μ΅œκ·Όμ—λŠ” fetch() APIλ₯Ό μ‚¬μš©ν•œλ‹€.

πŸ’‘ XMLμ΄λž€?

Tagλ₯Ό μ΄μš©ν•΄ 데이터λ₯Ό λ‚˜νƒ€λ‚΄λŠ” λ§ˆν¬μ—… μ–Έμ–΄ 쀑 ν•˜λ‚˜
λΆˆν•„μš”ν•œ νƒœκ·Έλ“€μ΄ 많이 λ“€μ–΄κ°€ 파일 μ‚¬μ΄μ¦ˆκ°€ 컀지며, 가독성도 쒋지 μ•Šλ‹€

πŸ’‘ AJAX와 XHR에 λͺ¨λ‘ XML이 λ“€μ–΄κ°„λ‹€. κ·Έλ ‡λ‹€λ©΄ μ„œλ²„μ™€ 데이터λ₯Ό 주고받을 λ•ŒλŠ” XML만 κ°€λŠ₯ν•œ 것인가?

μ•„λ‹ˆμ˜€. λ‹€μ–‘ν•œ 파일 포맷을 주고받을 수 μžˆλ‹€.
κ·Έ 쀑 ν•˜λ‚˜κ°€ JSON이닀.

λ‹€λ§Œ, AJAXκ³Ό XHR에 λͺ¨λ‘ XML이 λ“€μ–΄κ°€λŠ” 것은 이듀이 개발되던 λ‹Ήμ‹œ κ°œλ°œνŒ€μ΄ XML을 μ‚¬μš©ν•˜κ³  μžˆμ—ˆκΈ° λ•Œλ¬Έμ΄λ‹€.

3) JSON(JavaScript Object Notation)

  • ν‚€-κ°’ 쌍으둜 이루어진, κ²½λŸ‰μ˜ 데이터 κ΅ν™˜ κ·œμΉ™(데이터 포맷)

  • 'λΈŒλΌμš°μ €λ‚˜ λͺ¨λ°”μΌμ—μ„œ μ„œλ²„μ™€ 데이터λ₯Ό 주고받을 λ•Œ' ν˜Ήμ€ μ„œλ²„μ™€ ν†΅μ‹ ν•˜μ§€ μ•Šμ•„λ„ '였브젝트λ₯Ό 파일 μ‹œμŠ€ν…œμ— μ €μž₯ν•  λ•Œ' μ‚¬μš©ν•  수 μžˆλ‹€

  • μ‚¬λžŒ 눈으둜 읽기 νŽΈν•˜λ©°, ν…μŠ€νŠΈ(string)λ₯Ό 기반으둜 ν•΄ 가볍닀

  • μ„œλ²„μ™€ 데이터λ₯Ό 주고받을 λ•Œ 데이터λ₯Ό μ§λ ¬ν™”ν•˜κ³  μ „μ†‘ν•˜λŠ” 데 μ‚¬μš©λœλ‹€

  • ν”„λ‘œκ·Έλž˜λ° μ–Έμ–΄λ‚˜ ν”Œλž«νΌμ— 상관없이 μ‚¬μš©ν•  수 μžˆλ‹€.

πŸ’‘ λΈŒλΌμš°μ €μ™€ μ„œλ²„κ°€ JSON을 μ΄μš©ν•΄ ν†΅μ‹ ν•˜λŠ” κ³Όμ •

였브젝트λ₯Ό μ„œλ²„μ— μ „μ†‘ν•˜κΈ° μœ„ν•΄μ„œλŠ” 직렬화(serialize)λ₯Ό ν•΄μ•Ό ν•œλ‹€. μ§λ ¬ν™”λž€ 였브젝트λ₯Ό, { key: value } ν˜•νƒœμ˜ ν…μŠ€νŠΈ 즉 JSON으둜 λ³€ν™˜ν•˜λŠ” 것을 λ§ν•œλ‹€.

JSON으둜 μ§λ ¬ν™”λœ 였브젝트λ₯Ό λΈŒλΌμš°μ €μ— ν‘œκΈ°ν•˜κΈ° μœ„ν•΄μ„œλŠ” 역직렬화(deserialize)λ₯Ό ν•΄μ•Ό ν•œλ‹€. μ—­μ§λ ¬ν™”λž€ { key: value } ν˜•νƒœμ˜ ν…μŠ€νŠΈ 즉 JSON을, 였브젝트둜 λ‹€μ‹œ λ³€ν™˜ν•˜λŠ” 것을 λ§ν•œλ‹€.

4) 직렬화(serialization)

JSON.stringify()λ₯Ό μ‚¬μš©ν•˜μ—¬ μžλ°”μŠ€ν¬λ¦½νŠΈ κ°’μ΄λ‚˜ 였브젝트λ₯Ό JSON λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•  수 μžˆλ‹€.

πŸ”Ž boolean β†’ json

let json = JSON.stringify(true);
console.log(json); // true
console.log(typeof json); // string

πŸ”Ž λ°°μ—΄ β†’ json

  • JSONμ—μ„œλŠ” ''κ°€ μ•„λ‹ˆλΌ ""λ₯Ό μ‚¬μš©ν•œλ‹€.
json = JSON.stringify(['apple', 'banana']);
console.log(json);
// ["apple", "banana"] β†’ λ°°μ—΄μ²˜λŸΌ λ³΄μ΄μ§€λ§Œ, λ¬Έμžμ—΄μ΄λ‹€. 
console.log(typeof json); // string

πŸ”Ž 였브젝트 β†’ json

  • ν•¨μˆ˜(μ˜€λΈŒμ νŠΈμ— μžˆλŠ” 데이터 x)와 Symbol(μžλ°”μŠ€ν¬λ¦½νŠΈμ—λ§Œ μžˆλŠ” νŠΉλ³„ν•œ 데이터)이 json으둜 λ³€ν™˜λ  λ•ŒλŠ”, 객체 μ•ˆμ— μžˆμ„ 경우 μƒλž΅λ˜κ³ , λ°°μ—΄ μ•ˆμ— μžˆμ„ 경우 null둜 λ³€ν™˜λœλ‹€.
const rabbit = {
  name: 'happy',
  color: 'white',
  size: null,
  birthDate: new Date(),
  symbol: Symbol("id"), // json λ³€ν™˜ μ‹œ μƒλž΅
  jump : () => { // json λ³€ν™˜ μ‹œ μƒλž΅
    console.log('you can jump!');
  },
};

json = JSON.stringify(rabbit);
console.log(json);
// {"name":"happy","color":"white","size":null,"birthDate":"2021-10-11T06:28:27.059Z"}
console.log(typeof json); // string

πŸ’‘ replacer

MDN μ‚¬μ΄νŠΈ μ°Έκ³ 

  • JSON.stringify()의 λ§€κ°œλ³€μˆ˜λ‘œ replacerλ₯Ό μΆ”κ°€ν•¨μœΌλ‘œμ¨ JSON λ¬Έμžμ—΄μ„ μ’€ 더 μ„Έλ°€ν•˜κ²Œ ν†΅μ œν•  μˆ˜λ„ μžˆλ‹€.

  • replacerλŠ” ν•¨μˆ˜ λ˜λŠ” 배열이 될 수 μžˆλ‹€.

  • replacerλŠ”, JSON λ¬Έμžμ—΄μ— μΆ”κ°€λ˜μ–΄μ•Ό ν•˜λŠ” 값을, λ°˜ν™˜ν•΄μ•Ό ν•œλ‹€. return value;

  • replacerκ°€ undefinedλ₯Ό λ°˜ν™˜ν•˜λ©΄, κ·Έ 속성은 JSON λ¬Έμžμ—΄ 결과에 ν¬ν•¨λ˜μ§€ μ•ŠλŠ”λ‹€.

  • replacer 값이 null μ΄κ±°λ‚˜ μ œκ³΅λ˜μ§€ μ•ŠμœΌλ©΄, 객체의 λͺ¨λ“  속성듀이 JSON λ¬Έμžμ—΄ 결과에 ν¬ν•¨λœλ‹€. (Symbol, ν•¨μˆ˜ λ“± μ œμ™Έ)

πŸ”Ž replacerκ°€ 배열인 경우

  • λ°°μ—΄μ˜ μš”μ†ŒλŠ” '속성'이어야 ν•œλ‹€.
  • ν•΄λ‹Ή 속성과 κ·Έ κ°’λ§Œμ΄ JSON에 ν¬ν•¨λœλ‹€.
json = JSON.stringify(rabbit, ['name', 'size', 'color']);
console.log(json); // {"name":"tori","size":null,"color":"white"}

πŸ”Ž replacerκ°€ 콜백 ν•¨μˆ˜μΈ 경우

  • λ§€κ°œλ³€μˆ˜λ‘œλŠ” 'λ¬Έμžμ—΄ν™” 될 key와 value'λ₯Ό λ°›λŠ”λ‹€.
  • 맨 μ²˜μŒμ—λŠ” λ¬Έμžμ—΄ν™” 될 객체 μžμ²΄κ°€, 이λ₯Ό λ‚˜νƒ€λ‚΄λŠ” λΉ„μ–΄ μžˆλŠ” κ·Έ key와 ν•¨κ»˜ ν˜ΈμΆœλœλ‹€. πŸ“Œ
    κ·Έ λ‹€μŒμ—λŠ” λ¬Έμžμ—΄ν™” 될 κ·Έ 객체의 각 속성에 λŒ€ν•˜μ—¬ ν˜ΈμΆœλœλ‹€.
// replacer의 λ§€κ°œλ³€μˆ˜(key, value)κ°€ 무엇을 μ˜λ―Έν•˜λŠ”μ§€ μ•Œμ•„λ³΄μž

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`${key}, ${value}`);
  return value;
});

// console μ°½ κ²°κ³Ό

/*
, [object Object] πŸ“Œ λ¬Έμžμ—΄ν™” 될 객체 μžμ²΄κ°€, λΉ„μ–΄ μžˆλŠ” κ·Έ key와 ν•¨κ»˜ 호좜됨
name, happy
color, white
size, null
birthDate, 2021-10-11T07:42:51.692Z
jump, () => {
    console.log(`${name} can jump!`);
  }
*/
  • key와 valueκ°€ replacer(콜백 ν•¨μˆ˜)λ₯Ό ν•œ λ²ˆμ”© κ±°μ³€λ‹€κ°€ JSON으둜 바뀐닀
/* μ˜ˆμ‹œ 1 */
json = JSON.stringify(rabbit, (key, value) => {
  return key === 'name' ? 'syong' : value; 
});

console.log(json);
// {name: 'syong', color: 'white', size: null, birthDate: Mon Oct 11 2021 16:32:18 GMT+0900 (ν•œκ΅­ ν‘œμ€€μ‹œ), jump: Ζ’}

/* μ˜ˆμ‹œ 2 */
json = JSON.stringify(rabbit, (key, value) => {
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
});

console.log(json); // {"size":null}

5) 역직렬화(deserialization)

JSON.parse()λ₯Ό μ‚¬μš©ν•˜μ—¬ JSON λ¬Έμžμ—΄μ˜ ꡬ문을 λΆ„μ„ν•˜κ³ , μžλ°”μŠ€ν¬λ¦½νŠΈ κ°’μ΄λ‚˜ 였브젝트λ₯Ό 생성할 수 μžˆλ‹€.

json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj);
// {name: 'happy', color: 'white', size: null, birthDate: '2021-10-11T11:31:25.142Z'}

πŸ’‘ 주의!

직렬화λ₯Ό 톡해 λ§Œλ“€μ–΄μ§„ JSON λ¬Έμžμ—΄μ—λŠ” jump ν•¨μˆ˜κ°€ ν¬ν•¨λ˜μ§€ μ•Šμ•˜μœΌλ―€λ‘œ 역직렬화λ₯Ό 톡해 λ§Œλ“€μ–΄μ§„ μ˜€λΈŒμ νŠΈμ—λ„ jump ν•¨μˆ˜λŠ” ν¬ν•¨λ˜μ–΄ μžˆμ§€ μ•Šλ‹€. λ”°λΌμ„œ, jump() λ©”μ„œλ“œλ₯Ό μ‹€ν–‰ν•˜λ©΄ 였λ₯˜κ°€ λœ¬λ‹€.

λ§ˆμ°¬κ°€μ§€λ‘œ, 직렬화λ₯Ό 톡해 λ§Œλ“€μ–΄μ§„ JSON λ¬Έμžμ—΄μ—μ„œ birthDate μ†μ„±μ˜ 값이 Date 객체가 μ•„λ‹ˆλΌ λ¬Έμžμ—΄μ΄μ—ˆμœΌλ―€λ‘œ 역직렬화λ₯Ό 톡해 λ§Œλ“€μ–΄μ§„ μ˜€λΈŒμ νŠΈμ—μ„œλ„ birthDate μ†μ„±μ˜ 값은 λ¬Έμžμ—΄μ΄λ‹€. λ”°λΌμ„œ, getDate() λ©”μ„œλ“œλ₯Ό μ‹€ν–‰ν•˜λ©΄ 였λ₯˜κ°€ λœ¬λ‹€.

console.log(rabbit.jump()); // you can jump!
console.log(obj.jump()); // not a function 였λ₯˜

console.log(rabbit.birthDate.getDate()); // 11
console.log(obj.birthDate.getDate()); // not a function 였λ₯˜

πŸ’‘ reviver

  • JSON.parse()의 λ§€κ°œλ³€μˆ˜λ‘œ reviver ν•¨μˆ˜λ₯Ό μΆ”κ°€ν•¨μœΌλ‘œμ¨ 였브젝트λ₯Ό μ’€ 더 μ„Έλ°€ν•˜κ²Œ ν†΅μ œν•  μˆ˜λ„ μžˆλ‹€.
const obj = JSON.parse(json, (key, value) => {
  return key === 'birhDate' ? new Date(value) : value;
});

console.log(obj.birthDate.getDate); // 11

cf. μ•Œμ•„λ‘λ©΄ μœ μš©ν•œ μ‚¬μ΄νŠΈ

β‘  JSON Diff : μ„œλ²„μ— μš”μ²­ν•΄μ„œ λ°›μ•„μ˜¨ 2개의 데이터가 λ‹€λ₯Έ 곳이 μ–΄λ”˜μ§€λ₯Ό μ•Œλ €μ€Œ

β‘‘ JSON Beautifier : μ„œλ²„μ—μ„œ λ°›μ•„μ˜¨ JSON을 볡뢙할 λ•Œ 포맷이 망가진 경우 μ›μƒλ³΅κ·€μ‹œμΌœμ€Œ

β‘’ JSON Parser : JSON을 였브젝트 ν˜•νƒœλ‘œ λ°”κΏ”μ€Œ

β‘£ JSON Validator : JSONμ—μ„œ 였λ₯˜κ°€ λ°œμƒν•œ 곳을 μ•Œλ €μ€Œ


3. 콜백 ν•¨μˆ˜

1) 동기적 vs 비동기적

μžλ°”μŠ€ν¬λ¦½νŠΈλŠ” 동기적이닀.
동기적(synchronous) : μš”μ²­κ³Ό κ²°κ³Όκ°€ λ™μ‹œμ— 일어남
즉, μžλ°”μŠ€ν¬λ¦½νŠΈ μ½”λ“œλŠ”, ν˜Έμ΄μŠ€νŒ…μ΄ 된 ν›„μ—λŠ”, μž‘μ„±λœ μˆœμ„œμ— 따라 λ™κΈ°μ μœΌλ‘œ μ‹€ν–‰λœλ‹€.

cf. ν˜Έμ΄μŠ€νŒ…(hoisting)
λ³€μˆ˜ var와 ν•¨μˆ˜ 선언식이 μžλ™μœΌλ‘œ 제일 μœ„λ‘œ μ˜¬λΌκ°€λŠ” 것

console.log(1);
console.log(2);
console.log(3);

// 1
// 2
// 3

ν•œνŽΈ,
비동기적(asynchronous) : μš”μ²­κ³Ό κ²°κ³Όκ°€ λ™μ‹œμ— μΌμ–΄λ‚˜μ§€ μ•ŠμŒ
즉, μ½”λ“œκ°€ μ–Έμ œ 싀행될지 μ˜ˆμΈ‘ν•  수 μ—†μŒμ„ μ˜λ―Έν•œλ‹€.

console.log(1);
setTimeout(() => console.log(2), 1000);
console.log(3);

// 1
// 3
// 2

2) 동기적 콜백 ν•¨μˆ˜ vs 비동기 콜백 ν•¨μˆ˜

πŸ’‘ synchronous callback

function printImmediately (print) {
  print();
}

printImmediately(() => console.log('sync callback'));

πŸ’‘ asynchronous callback

비동기 콜백 ν•¨μˆ˜λ₯Ό 포함해, μœ„μ˜ μ˜ˆμ‹œλ“€μ„ μ „λΆ€ ν•©μ³μ„œ μ•„λž˜μ™€ 같이 μž‘μ„±λ˜μ–΄ μžˆλ‹€κ³  ν•˜μž.

'use strict';

console.log(1);
setTimeout(() => console.log(2), 1000);
console.log(3);

function printImmediately (print) {
  print();
}

printImmediately(() => console.log('sync callback'));

function printWithDelay (print, timeout) { // setTimeout을 wrappingν•˜κ³  μžˆλŠ” ν•¨μˆ˜
  setTimeout(print, timeout);
}

printWithDelay(() => console.log('async callback'), 2000);

이 μ½”λ“œλ₯Ό μžλ°”μŠ€ν¬λ¦½νŠΈ 엔진은 μ•„λž˜μ™€ 같이 μ΄ν•΄ν•œλ‹€.

'use strict';

// ν•¨μˆ˜ 선언식 ν˜Έμ΄μŠ€νŒ…(hoisting)
function printImmediately (print) {
  print();
}

function printWithDelay (print, timeout) {
  setTimeout(print, timeout);
}

console.log(1); // 동기적 μ‹€ν–‰
setTimeout(() => console.log(2), 1000); // 비동기적 μ‹€ν–‰
console.log(3); // 동기적 μ‹€ν–‰

printImmediately(() => console.log('sync callback')); // 동기적 μ‹€ν–‰

printWithDelay(() => console.log('async callback'), 2000); // 비동기적 μ‹€ν–‰

// 1
// 3
// sync callback
// 2
// async callback

3) 콜백 지μ˜₯

콜백 ν•¨μˆ˜ 쀑첩 μ‚¬μš©μ„ μ˜λ―Έν•œλ‹€

예제

  • μ‚¬μš©μžμ—κ²Œ id와 password μž…λ ₯ 값을 받아와라

  • id와 passwordλ₯Ό μ΄μš©ν•΄ μ„œλ²„μ— 둜그인 λ˜λ„λ‘ μš”μ²­ν•΄λΌ
    (μ„œλ²„μ™€μ˜ 톡신은 setTimeout ν•¨μˆ˜λ‘œ λŒ€μ²΄ν•΄λΌ)

  • λ‘œκ·ΈμΈμ„ μ„±κ³΅μ μœΌλ‘œ ν–ˆλ‹€λ©΄
    λ‘œκ·ΈμΈν•œ μ‚¬μš©μžμ˜ idλ₯Ό μ΄μš©ν•΄ μ‚¬μš©μžμ˜ rolesλ₯Ό μš”μ²­ν•΄ 받아와라

  • rolesκ°€ μ„±κ³΅μ μœΌλ‘œ λ°›μ•„μ‘Œλ‹€λ©΄
    ν΄λΌμ΄μ–ΈνŠΈλŠ” μ‚¬μš©μžμ˜ 이름과 역할이 λ“€μ–΄ μžˆλŠ” 였브젝트λ₯Ό 가지고 μžˆμ„ 것, 이λ₯Ό 좜λ ₯해라

class UserStorage {
  loginUser (id, password, onSuccess, onError) {
	setTimeout(() => {
      if (id === 'syong' && password === 'happy' ||
          id === 'corder' && password === 'nice') {
        onSuccess(id);
      } else {
        onError(new Error('not found'));
      }
    }, 2000);
  }
  
  getRoles (user, onSuccess, onError) {
	setTimeout(() => {
      if (user === 'syong') {
        onSuccess({ name: 'syong', role: 'admin' });
      } else {
        onError(new Error('no access'));
      }
    }, 1000);
  }
}

const userStorage = new UserStorage();

const id = prompt('idλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”');
const password = prompt('passwordλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”');

userStorage.loginUser(id, password, user => {
  userStorage.getRoles(user, userWithRoles => {
    alert(`${userWithRoles.role} ${userWithRoles.name}λ‹˜, ν™˜μ˜ν•©λ‹ˆλ‹€!`);
  }, error => {
    throw error;
  });
}, error => {
  throw error;
});

μ΄λ ‡κ²Œ μž‘μ„±ν•˜λ©΄ 가독성이 맀우 쒋지 μ•Šμ•„ 디버깅과 μœ μ§€Β·λ³΄μˆ˜λ₯Ό ν•˜κΈ°κ°€ 맀우 μ–΄λ ΅λ‹€.


✨ 내일 ν•  것

  1. κ°•μ˜ 계속 λ“£κΈ° (promise, async, await)
profile
λŠ₯λ™μ μœΌλ‘œ μ‚΄μž, ν–‰λ³΅ν•˜κ²ŒπŸ˜

0개의 λŒ“κΈ€