every, some

이효범·2022년 4월 5일
0

ES6 - OOP & FRP

목록 보기
5/15
post-thumbnail

Array는 Array Class의 인스턴스이다. 따라서 Array Class에 정의되어 있는 메소드들을 활용할 수 있다. 주인장은 Array의 헬퍼 메소드들을 통해 OOP와 FRP의 기초에 대해 공부해보려 한다.

every, sum

다음과 같은 상황이 있다.
heroes 모두 중국집에 가서 무사히 짜장면을 먹을 수 있을것인가?

let heroes = [
    { balance: 5000, id: 1, name: 'superman', type: 'Flying', cost: 400 },
    { balance: 7000, id: 2, name: 'batman', type: 'Flying', cost: 320 },
    { balance: 9000, id: 11, name: 'batman', type: 'Flying', cost: 320 },
    { balance: 3000, id: 3, name: 'X-man', type: 'Mutant', cost: 200 },
    { balance: 1000, id: 4, name: 'Ironman', type: 'Metal', cost: 530 },
    { balance: 6000, id: 5, name: 'Antman', type: 'Insect', cost: 180 },
];
let comments = [
    { idOfWriter: 1, content: '아름다운 우리 나라' },
    { idOfWriter: 2, content: '아름다운 박쥐 나라' },
    { idOfWriter: 1, content: '아름다운 크립톤' },
    { idOfWriter: 3, content: '아름다운 장미 한송이' },
    { idOfWriter: 5, content: '아름다운 제주도 밤바다' },
    { idOfWriter: 4, content: '아름다운 제주도 한라산' },
    { idOfWriter: 4, content: '아름다운 올레길' },
    { idOfWriter: 2, content: '아름다운 돌담길' },
];

// heroes 는 식사를 하려고 한다.
// 짜장면은 한 그릇에 5000원이다.
// heroes 모두 다 이 중국집에가서 짜장면을 시켜먹을 수 있는지 없는지를 확인해보자.

짜장면을 먹을 수 있는지, 없는지를 판단하는 메카니즘을 Impelative방식과 Declarative방식으로 한번 구현해보자. X-man과 Ironman은 열심히 일을 하지 않아서 5000원 이하의 급여를 받는다. 따라서 회식 장소는 중국집이 될 수 없다.

// Imperative
let AllEatZzajang = true;
let NotAllEatZzajang = false;
for (let i = 0; i < heroes.length; i++) {
  if (heroes[i].balance < 5000) {
   AllEatZzajang = false;
   NotAllEatZzajang = true;
 }
}
console.log(AllEatZzajang);
console.log(NotAllEatZzajang);
// Declarative, fat arrow
let AllEatZzajang = heroes.every(hero => hero.balance >= 5000);
console.log(AllEatZzajang);  // false

some은 every와 비슷한데 약간 다르다. some은 5000원 보다 적은 급여를 받는 hero가 있느냐? 라고 물어보는 것이다. 한 명이라도 존재한다면 true를 반환한다. 이와 반대로 every는 말 그대로 모두가 조건을 만족해야만 true를 반환한다.

// Declarative, fat arrow
let EatZzajang = heroes.some(hero => hero.balance >= 5000);
console.log(EatZzajang);  // true

every, some 연습

1. 첫번째 연습문제

// 1.return 'true' if every user has submitted a login form.
let loginForm = [
    { id: 41, hasSubmitted: true },
    { id: 62, hasSubmitted: false },
    { id: 84, hasSubmitted: true },
];

let loginFormSubmitted;

소스 코드

loginFormSubmitted = loginForm.every(form => form.hasSubmitted === true);
console.log(loginFormSubmitted);

2. 두번째 연습문제

// 2. assign the boolean 'true' to the variable 'inProgress' if any network request has a 'status' of 'pending'.
let httpRequests = [
    { url: '/photos', status: 'complete' },
    { url: '/albums', status: 'pending' },
    { url: '/users', status: 'failed' },
];

let inProgress;

소스 코드

inProgress = httpRequests.some(req => req.status === 'pending');
console.log(inProgress);
profile
I'm on Wave, I'm on the Vibe.

0개의 댓글