막학기에 졸프 하나만 듣고 등교를 안하게 되어서 자꾸 게을러지게 되는것 같아서 부트캠프에 들어가게 되었다. 프론트엔드 + sql + 백엔드 과정으로 이어지고 팀 프로젝트를 총 2번해서 많이 배울 수 있을 것 같다고 생각했다.
처음 커리큘럼은 JS로 공부를 하긴 해봤지만,아직 많이 부족한 점을 깨닫게 되었다.
이번에 새롭게 알게 되었거나 헷갈리는 부분들을 정리하고 회고하려고 한다.
> %DebugPrint(h)
DebugPrint: 0xb172ecef8d9: [String] in OldSpace: #Hello
0xa12be380691: [Map] in ReadOnlySpace
- map: 0x0a12be380841 <MetaMap (0x0a12be380099 <null>)>
- type: INTERNALIZED_ONE_BYTE_STRING_TYPE
- instance size: variable
- elements kind: HOLEY_ELEMENTS
- enum length: invalid
- stable_map
- non-extensible
- back pointer: 0x0a12be380069 <undefined>
- prototype_validity cell: 0
- instance descriptors (own) #0: 0x0a12be380c91 <DescriptorArray[0]>
- prototype: 0x0a12be380099 <null>
- constructor: 0x0a12be380099 <null>
- dependent code: 0x0a12be380c51 <Other heap object (WEAK_ARRAY_LIST_TYPE)>
- construction counter: 0
'Hello'
> > %DebugPrint(h2)
DebugPrint: 0x35d9d63f629: [String] in OldSpace: #hi
0xa12be380691: [Map] in ReadOnlySpace
- map: 0x0a12be380841 <MetaMap (0x0a12be380099 <null>)>
- type: INTERNALIZED_ONE_BYTE_STRING_TYPE
- instance size: variable
- elements kind: HOLEY_ELEMENTS
- enum length: invalid
- stable_map
- non-extensible
- back pointer: 0x0a12be380069 <undefined>
- prototype_validity cell: 0
- instance descriptors (own) #0: 0x0a12be380c91 <DescriptorArray[0]>
- prototype: 0x0a12be380099 <null>
- constructor: 0x0a12be380099 <null>
- dependent code: 0x0a12be380c51 <Other heap object (WEAK_ARRAY_LIST_TYPE)>
- construction counter: 0
'hi'> %DebugPrint(h9)
DebugPrint: 0xb172ecef8d9: [String] in OldSpace: #Hello
0xa12be380691: [Map] in ReadOnlySpace
- map: 0x0a12be380841 <MetaMap (0x0a12be380099 <null>)>
- type: INTERNALIZED_ONE_BYTE_STRING_TYPE
- instance size: variable
- elements kind: HOLEY_ELEMENTS
- enum length: invalid
- stable_map
- non-extensible
- back pointer: 0x0a12be380069 <undefined>
- prototype_validity cell: 0
- instance descriptors (own) #0: 0x0a12be380c91 <DescriptorArray[0]>
- prototype: 0x0a12be380099 <null>
- constructor: 0x0a12be380099 <null>
- dependent code: 0x0a12be380c51 <Other heap object (WEAK_ARRAY_LIST_TYPE)>
- construction counter: 0
'Hello' ⇒ h1와 h9가 변수 이름은 다르지만 값(”Hello”)로 같으므로 주소가 0xb172ecef8d9 로 동일함 ⇒ hash를 돌리면 모두 값이 같기 때문에 한번만 만들어서 메모리 절약문자열은 원시 타입이므로 불변
h9를 “hi” 로 값을 바꾸면 기존 0xb172ecef8d9 의 내용이 바뀌는 것이 아니라, 새로운 메모리 주소에 hi를 만들고 그곳을 가리키게 됨
⇒ 배열처럼 .push()같은 메서드로 원본을 직접 수정하는 것이 불가능
메모리 공간인 stack과 heap을 어떻게 사용하는지의 차이
| 구분 | 원시 타입 (Primitive) | 객체 타입 (Object/Reference) |
|---|---|---|
| 종류 | String, Number, Boolean, null, undefined, Symbol | Array, Function, Object |
| 저장 위치 | Call Stack에 값 자체가 저장됨 (혹은 상수는 별도 풀) | Heap에 실제 데이터 저장, Stack에는 그 주소(참조값) 저장 |
| 특징 | 불변 (Immutable). 값이 바뀌면 주소가 바뀜. | 가변 (Mutable). 참조 주소는 그대로 두고 힙의 데이터만 수정 가능. |
O(n)O(1)() ⇒ () ⇒ {}(theme) ⇒ (onClick) ⇒ {}function multiple(a: number, b: number) {
return a * b;
}
const CONSTANT = 2;
const test1 = multiple(CONSTANT, 1); // 2
const test2 = multiple(CONSTANT, 2); // 4
const test3 = multiple(CONSTANT, 3); // 6
const test4 = multiple(CONSTANT, 4); // 8
const test5 = multiple(CONSTANT, 5); // 10function multiple(a: number) {
return function (b: number) {
return a * b;
};
}
const CONSTANT = 2;
const multipleWithConstant = multiple(CONSTANT);
const test1 = multipleWithConstant(1); // 2
const test2 = multipleWithConstant(2); // 4
const test3 = multipleWithConstant(3); // 6
const test4 = multipleWithConstant(4); // 8
const test5 = multipleWithConstant(5); // 10function multiple(a: number) {
return function (b: number) {
return a * b;
};
}function outer(a) {
const base = a;
return function inner(b) {
return base + b;
};
}function memoized(fn) {
const cache = [];
return function (k) {
return cache[k] ?? (cache[k] = fn(k));
};
}
// 함수 정의를 밖에서 하면 호출할 수 있으므로 밖에서 정의하지 않는다
// function facto(k) {
// return k;
// }
const memoizedFactorial = memoized(function (k) {
if (k === 1) return 1;
return k * memoizedFactorial(k - 1); // 클로저를 사용하기 -> 캐싱된 재귀
});globalThis.name = 'Global Name';
const obj = {
name: 'Obj Name',
printName() {
console.log(this.name);
},
};
const printName = obj.printName; // <f.o> address
// obj = null; 함수 주소만 들어가고 obj와 연결이 되지 않음
printName();
printName은 obj.printName을 가리킴obj.printName()const dog = {
name: 'Maxx',
showMyName() {
console.log(`My name is ${this.name}.`);
},
whatsYourName() {
setTimeout(this.showMyName, 1000);
}
};
dog.whatsYourName();
setTimeout)에서의 this 소실setTimeout
this.showMyName의 object에 대한 주소만 전달고치기 위해서는
~~this.~~showMyName.bind(this)var self = this;
setTimeout(function () {
self.showMyName();
}, 1000);setTimeout(() => {
this.showMyName();
}, 1000);const arr = ['1', '2', '3'];
const result = arr.map(parseInt);
console.log(result); // [1, NaN, NaN]
map이 넘겨주는 인자와 parseInt가 받는 인자의 개수가 다름map이 콜백 함수에게 넘겨주는 것: element, index, arrayparseInt가 받아서 쓰는 것: string, radix| 반복 횟수 | map이 넘긴 값 (값, 인덱스) | parseInt의 해석 (string, radix) | 결과 |
|---|---|---|---|
| 1 | ('1', 0) | 1을 0진법(10진법)으로 변환 | 1 |
| 2 | ('2', 1) | 2를 1진법으로 변환 | NaN |
| 3 | ('3', 2) | 3을 2진법으로 변환 | NaN |
const unary = fn => arg => fn(arg)
arr.map(unary(parseInt));
const myFetch = () =>
new Promise((resolve, reject) => // 잘못된 코드!!!!
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(res => res.json())
.then(resolve)
.catch(reject)
);const myFetch = async (url) =>
const res = await fetch(url);
return res.json();
// return await res.json();
// 잘못된 코드!! 어차피 async는 Promise를 반환! 2번 await을 할뿐...
);
const myFetch2 = async(url) =>
fetch(url).then(res => res.json());call stack에 otherFunction이 먼저 들어감…. 순서가 안맞음…..
let result;
promiseFn().then(res =>
result = res; // 순서 늦음!!!
);
otherFunction(result);
let result;
promiseFn().then(otherFunction);
// 단, next는 비동기, getRow는 동기 함수!
// https://npmtrends.com/mysql-vs-mysql2
const getAllUsers = (sql) =>
new Promise((resolve, reject) =>
query.execute(sql, (err, rs) => {
if (err) reject(err);
const results = [];
while (rs.next())
results.push(rs.getRow());
resolve(results);
});
);
execute(sqlStr, cb) {
conn.query(sqlStr)
.then(res => cb(null, res))
.catch(err => cb(err))
}
const getAllUsers = (sql) =>
new Promise((resolve, reject) =>
query.execute(sql, (err, rs) => {
if (err) reject(err);
const results = [];
(async function() {
do {
const row = await rs.next(); // promise
if (!row) break;
results.push(row);
} while(true);
)();
});
);
try {
randTime(1)
.then(res => res)
.then(res => {
console.log('res>>', res);
throw new Error('XXX');
})
.catch(err => {
console.log('error!!!', err);
throw err; // 어디로?!
});
} catch (Err) {
console.error('@@@@@@@Err>>', Err);
} randTime(1)
.then(res => res)
.then(res => {
console.log('res>>', res);
throw new Error('XXX');
})
.catch(err => {
console.log('error!!!', err);
throw err;
}).catch (Err => {
console.error('@@@@@@@Err>>', Err);
});function iter(vals) {
let i = -1;
return {
async next() {
i += 1;
// await 사용하지 않으면 undefined됨
return { value: await randTime(vals[i]), done: i >= 3 };
},
};
}
(async function () {
const it = iter([1, 2, 3]);
console.time('iter');
console.log('1=', await it.next());
console.log('2=', await it.next());
console.log('3=', await it.next());
console.log('4=', await it.next());
console.timeEnd('iter');
})();
function* pAfterTime(sec) {
return yield afterTime(sec);
}
async function* asyncAfterTime(sec) {
return await afterTime(sec);
}
const pat = pAfterTime(1);
console.log('promise>>', pat.next());
const aat = asyncAfterTime(1);
console.log('async>>', await aat.next());
for await (const fao of arr.values()) {
console.log('fao=', fao);
}
원래 개발할 때 AI에 많이 의존하게 됐는데,
기왕 공부하기로 한거 과제할때 AI 사용하지말고 해보자는 마음으로 풀었다. 개념도 어려웠지만, 실제로 연습 문제를 풀 때는 더 어려웠다..
아직 많이 부족한게 느껴져서 현타가 오긴 했지만,
그만큼 더 열심히 반복해서 풀어보고 술술 풀 수 있을 때까지 연습해야겠다고 느꼈다.