Skip to content

[3주차] 익명 함수 표현식, 기명 함수 표현식 #11

@poco111

Description

@poco111

주제

  • 책의 필자는 프로그램 내에 있는 함수는 목적이 있어야 한다고 생각하며, 목적을 설명하는 함수 이름을 부여해야한다고 생각한다.
  • 따라서, 익명 함수 표현식 보다는 기명 함수 표현식을 선호한다고 한다.
  • 또한, 같은 골자로 화살표 함수 역시 특별한 목적(this 키워드가 참조하는 렉시컬 환경을 핸들링 하기 등)이 아니라면 선호하지 않는다고 한다.

선정 이유

  • 간편하고 짧게 작성할 수 있기 때문에 화살표 함수를 주로 사용했는 데, 책의 필자와 같은 관점을 처음 접해서 이야기해보고 싶음

책 내용 (p페이지)

  • 115p ~ 116p

과제

B.1 비교 연습하기

// B.1 비교 연습하기

const dayStart = '07:30';
const dayEnd = '17:45';

const getTime = (time) => {
  const [hour, minute] = time.split(':');

  return parseInt(hour) * 60 + parseInt(minute);
};

const scheduleMeeting = (startTime, durationMinutes) => {
  const dayStartTime = getTime(dayStart);
  const dayEndTime = getTime(dayEnd);

  const meetingStartTime = getTime(startTime);
  const meetingEndTime = meetingStartTime + durationMinutes;

  return meetingEndTime <= dayEndTime && meetingStartTime >= dayStartTime;
};

console.log(scheduleMeeting('7:00', 15)); // false
console.log(scheduleMeeting('07:15', 30)); // false
console.log(scheduleMeeting('7:30', 30)); // true
console.log(scheduleMeeting('11:30', 60)); // true
console.log(scheduleMeeting('17:00', 45)); // true
console.log(scheduleMeeting('17:30', 30)); // false
console.log(scheduleMeeting('18:00', 15)); // false

// 매개변수
// startTime : "hh:mm" 형태의 회의 시작시간
// durationMinutes : 회의 지속 시간

// 출력
// 회의가 근무시간 내에 이뤄질 경우 true, 아니면 false 반환

B.2 클로저 연습하기

// B.2 클로저 연습하기
// range 함수는 두 개의 숫자 인자를 받는다.
// 두 숫자는 각각 원하는 범위의 시작과 끝을 나타낸다.
// 두 번째 인자가 없는 경우에는 두 번째 인자를 넘길 수 있도록 하는 함수가 반환되어야 한다.
const countRange = (num1, num2) => {
  const answer = [];
  if (num2 === 0) return answer;

  for (let i = num1; i <= num2; i++) {
    answer.push(i);
  }

  return answer;
};

const range = (start, end) => {
  return end !== undefined
    ? countRange(start, end)
    : (end) => {
        return countRange(start, end);
      };
};

console.log(range(3, 3)); // [3]
console.log(range(3, 8)); // [3,4,5,6,7,8]
console.log(range(3, 0)); // []

const start3 = range(3);
const start4 = range(4);

console.log(start3(3)); // [3]
console.log(start3(8)); // [3,4,5,6,7,8]
console.log(start3(0)); // []

console.log(start4(6)); // [4,5,6]

B.3 프로토타입 연습하기

// B.3 프로토타입 연습하기
// Math.trunc는 주어진 숫자의 소수 부분을 제거하고 숫자의 정수 부분만을 반환하는 내장 함수

function randMax(max) {
  return Math.trunc(1e9 * Math.random()) % max;
}

const reel = {
  symbols: ['♠', '♥', '♦', '♣', '☺', '★', '☾', '☀'],
  spin() {
    if (this.position == null) {
      this.position = randMax(this.symbols.length - 1);
    }
    this.position = (this.position + 100 + randMax(100)) % this.symbols.length;
  },
  display() {
    if (this.position == null) {
      this.position = randMax(this.symbols.length - 1);
    }
    return this.symbols[this.position];
  },
};

const slotMachine = {
  reels: [Object.create(reel), Object.create(reel), Object.create(reel)],
  spin() {
    this.reels.forEach((reel) => reel.spin());
  },
  display() {
    const lines = [];

    for (let i = 0; i < 3; i++) {
      const slotLine = this.reels.map((reel) => {
        const slot = Object.create(reel);
        slot.position =
          (reel.symbols.length + reel.position + i) % reel.symbols.length;
        return slot.display();
      });

      lines.push(slotLine.join('|'));
    }
    return lines.join('\n');
  },
};

slotMachine.spin();
console.log(slotMachine.display());
// ☾ | ☀ | ★
// ☀ | ♠ | ☾
// ♠ | ♥ | ☀

slotMachine.spin();
console.log(slotMachine.display());
// ♦ | ♠ | ♣
// ♣ | ♥ | ☺
// ☺ | ♦ | ★

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions