1) typeof null 또한 "object" 이므로
객체일 경우의 조건문 사용시 주의하기
❌ if (typeof collection === "object")
↓
✅ if (typeof collection === "object" && collection !== null)
null
의 타입 또한 object
이기 때문에 typeof
만 사용해 객체인지 아닌지를 구분한다면 의도치 않게 작동할 수 있으므로 collection
이 null
이 아닐때의 조건도 추가되어야 할 것 같습니다.
2) 기본 코드 스타일 신경쓰고 제출하기 전 꼼꼼히 체크하기
❌ for (i = 0; i < collection.length; i++)
✅ for (let i = 0; i < collection.length; i++)
❌ if (n !== 0 && n!== undefined && array.length > n) {
✅ if (n !== 0 && n !== undefined && array.length > n) {
for문
에서 변수 선언 let
이 빠져있음.
if문
에서 n!= undefined
부분도 띄어쓰기 빠져있음
3) for...in문
for...in 문
은 객체의 프로토타입 체인까지 타고 올라가기 때문에 for..in문
을 사용할 경우, 프로토타입 체인의 속성까지 열거하게 됩니다.
이런 경우 Object.prototype.hasOwnProperty 를 사용해 가드를 해줄수 있습니다.
처음 작성했던 코드)
} else if (typeof collection === "object") {
for (const key in collection) {
// code..
피드백)
for (key in foo) {
if (Object.prototype.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
}
수정 코드)
for (key in collection) {
if (Object.prototype.hasOwnProperty.call(collection, key)) {
// code.. blah blah
}
}
위와 같이 작성하여야 객체의 프로토타입 체인까지 가는 것을 가드해 줄 수 있음.
4) 매개변수 재할당 ❌
매개변수엔 arguments
객체가 있기 때문에 매개변수를 직접적으로 수정하면 arguments
객체 또한 변경될 수 있다.
따라서 매개변수를 바로 재할당 해주지 않고 배열을 복사한 후 사용하시는게 안전하다.
// 수정 전
_.reduce = function (collection, iterator, accumulator) {
if (accumulator === undefined) {
for (let i = 0; i < collection.length; i++) {
❌ accumulator = collection[0];
// 수정 코드
_.reduce = function (collection, iterator, accumulator) {
let accumulatorCopy = accumulator;
let collectionCopy = collection;
if (typeof collection === "object" && collection !== null) {
collectionCopy = Object.values(collectionCopy);
}
if (accumulator === undefined) {
accumulatorCopy = collection[0];
collectionCopy = collection.slice(1)
}
for (let i = 0; i < collectionCopy.length; i++) {
accumulatorCopy = iterator(accumulatorCopy, collectionCopy[i]);
}
return accumulatorCopy;
};
위의 코드와 같이 값을 똑같이 복사해 준 뒤에 그 값을 이용하여 코드를 짜주는 것이 좋음
5) default parameter
default parameter
는
지금처럼 매개 변수의 값이 undefined 일 경우 대체할 값으로 초기화 하는 것을 의미한다.
// 수정 전
_.every = function (collection, iterator) {
if(iterator === undefined) {
iterator = _.identity;
}
// 수정 후 ✅
_.every = function (collection, iterator = _.identity) {
6) !!(not not operator) -> Boolean() 변환 가능
Boolean으로 형변환하는 방법에는 Boolean()을 사용하는 방법도 있다
!!iterator(item);
-> Boolean(iterator(item));