반복문 사용시 주의사항
- 한번만 하면 되는 명령문은 반복문 밖에서 작성하기
for (let i = 0; i < collection.length; i++) {
if (accumulator === undefined) {
accumulator = collection[0];
continue;
}
const iteratorResult = iterator(accumulator, collection[i]);
if (iteratorResult === undefined) {
continue;
}
accumulator = iteratorResult;
}
let index = accumulator === undefined ? 1 : 0;
accumulator = accumulator === undefined ? collection[0] : accumulator;
for (index; index < collection.length; index++) {
accumulator = iterator(accumulator, collection[index]);
}
같은 결과를 반환하는 조건문 합치기
if (iterator(item)) {
return true;
}
if (wasTrue) {
return true;
}
if (iterator(item) || wasTrue) {
return true;
}
some 메소드를 구현하는 방법
1. _.reduce 사용
_.some = function (collection, iterator = _.identity) {
return _.reduce(
collection,
function (wasTrue, item) {
if (iterator(item) || wasTrue) {
return true;
}
return false;
},
false
);
};
2. for 문 사용
- collection의 길이가 길어질 경우, reduce 메소드의 경우 collection 전체를 순회해야하므로 효율성이 떨어짐
- for 문과 break를 사용해서 조건문이 true값이 나올 때 for 문을 바로 나올 수 있게 함
_.some = function (collection, iterator = _.identity) {
let wasTrue = false;
for (let i = 0; i < collection.length; i++) {
if (iterator(collection[i])) {
wasTrue = true;
break;
}
}
return wasTrue;
}
for-in 문 사용시 주의사항
- for in문은 프로토타입 체인으로부터 상속된 것도 포함한 모든 열거 가능한 프로퍼티를 열거함
- 프로토타입 체인을 따라 상속된 프로퍼티를 걸러내기 위해hasOwnProperty() 메서드를 사용함
- Object.hasOwnProperty(key)
- Object.prototype.hasOwnProperty.call(object, key)
- object가 hasOwnProperty를 재정의하여 덮어쓴 경우에도 활용할 수 있음
for (let key in collection) {
iterator(collection[key], key, collection);
}
for (let key in collection) {
if (Object.prototype.hasOwnProperty.call(collection, key)) {
iterator(collection[key], key, collection);
}
}
참고 : for-in문과 hasOwnProperty()