14일차 class 연습문제

워니·2024년 10월 31일

✅ 24.10.31 (목)


1. 기본 클래스 생성

문제 1: Car 클래스를 정의하고, make, model, year를 인스턴스 변수로 갖도록 하세요. info 메서드를 추가하여 자동차 정보를 출력하도록 하세요.

기본 제공 코드:

class Car {
  constructor(make, model, year) {
    // 초기화 코드
  }
  info() {
    // 자동차 정보 출력 코드
  }
}
// 테스트 케이스
const car1 = new Car('Toyota', 'Camry', 2020);
console.log(car1.info()); // 2020 Toyota Camry

문제 풀이:

class Car {
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
  }
  info() {
    return `${this.year} ${this.make} ${this.model}`;
  }
}
const car1 = new Car("Toyota", "Camry", 2020);
console.log(car1.info()); // 2020 Toyota Camry

2. 상속

문제 2: Animal 클래스를 만들고, Dog 클래스를 Animal로부터 상속받게 하세요. Dog 클래스에 bark 메서드를 추가하세요.

기본 제공 코드:

// 테스트 케이스
const dog = new Dog('바둑이');
console.log(dog.introduce()); // 바둑이입니다.
console.log(dog.bark()); // 왈왈

문제 풀이:

class Animal {
  constructor(name) {
    this.name = name;
  }
  introduce() {
    return `${this.name}입니다.`;
  }
}
class Dog extends Animal {
  constructor(name) {
    super(name);
  }
  bark() {
    return "왈왈";
  }
}
// 테스트 케이스
const dog = new Dog("바둑이");
console.log(dog.introduce()); // 바둑이입니다.
console.log(dog.bark()); // 왈왈

3. 정적 메서드

문제 3: MathUtil 클래스를 만들어, 두 수의 최소값을 반환하는 정적 메서드 min을 작성하세요.

기본 제공 코드:

// 테스트 케이스
console.log(MathUtil.min(10, 20));

문제 풀이:

class MathUtil {
  static min(a, b) {
    return a < b ? a : b;
  }
}
console.log(MathUtil.min(10, 20));

✅ 24.10.31 (목)

`static`이 생각났지만, 사용방법을 잊음

4. 접근자 (Getter/Setter)

문제 4: Rectangle 클래스를 정의하고, widthheight를 속성으로 갖도록 하세요. area는 접근자로 구현하세요.

기본 제공 코드:

// 테스트 케이스
const rect = new Rectangle(5, 10);
console.log(rect.area); // 50

문제풀이:

class Rectangle {
  constructor(width, height) {
    this._width = width;
    this._height = height;
  }
  set width(value) {
    this._width = value > 0 ? value : 0;
  }
  set height(value) {
    this._height = value > 0 ? value : 0;
  }
  get area() {
    return this._width * this._height;
  }
}
const rect = new Rectangle(5, 10);
console.log(rect.area); // 50

✅ 24.10.31 (목)

set과 get 사용법 기억 못함

5. 클래스 메서드

문제 5: Counter 클래스를 만들어, 카운터를 증가시키는 클래스 메서드 increment와 현재 값을 반환하는 getValue 메서드를 추가하세요. 카운터의 초깃값은 0입니다.

기본 제공 코드:

// 테스트 케이스
Counter.increment();
console.log(Counter.getValue());

문제풀이:

class Counter {
  constructor() {
    this.count = 0;
  }
  increment() {
    this.count++;
  }
  getValue() {
    return this.count;
  }
}
const counter = new Counter();
counter.increment();
console.log(counter.getValue());

6. 프로토타입 확장

문제 6: Person 클래스를 정의하고, 프로토타입에 greet 메서드를 추가하세요.

기본 제공 코드:

// 테스트 케이스
const person = new Person('이순신');
console.log(person.greet()); // 이순신 안녕!

문제풀이:

class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `${this.name} 안녕!`;
  }
}
const person = new Person("이순신");
console.log(person.greet()); // 이순신 안녕!

7. 다형성

문제 7: Shape 클래스를 만들고, CircleRectangle 클래스를 상속받도록 하세요. 각각의 area 메서드를 오버라이드(오버라이딩)하세요.

기본 제공 코드:

// 테스트 케이스
const circle = new Circle(5);
console.log(circle.area());  // 5 * 5 * 3.14 
const rect = new Rect(5);
console.log(rect.area()); // 25 (5*5)

문제풀이:

class Shape {
  area(value) {
    return value;
  }
}
class Circle extends Shape {
  constructor(radius) {
    super();
    this.radius = radius;
  }
  area() {
    return this.radius * this.radius * 3.14;
  }
}
const circle = new Circle(5);
console.log(circle.area()); // 5 * 5 * 3.14
class Rect extends Shape {
  constructor(length) {
    super();
    this.length = length;
  }
  area() {
    return this.length * this.length;
  }
}
const rect = new Rect(5);
console.log(rect.area()); // 25 (5*5)

8. 인스턴스 메서드 체이닝

문제 8: Builder 클래스를 만들어, 여러 메서드를 체이닝할 수 있도록 하세요.

기본 제공 코드:

// 테스트 케이스
const builder = new Builder();
const result = builder.append('Hello, ').append('World!').getValue();
console.log(result); // Hello, World!

문제풀이:

class Builder {
  constructor() {
    this.value = "";
  }
  append(str) {
    this.value += str;
    return this;
  }
  getValue() {
    return this.value;
  }
}
const builder = new Builder();
const result = builder.append("Hello, ").append("World!").getValue();
console.log(result); // Hello, World!

✅ 24.10.31 (목)

`constructor` 안에 `value` 안 넣음, `value` 정의 애매함

9. 클래스의 인스턴스 수 추적

문제 9: Book 클래스를 정의하고, 생성될 때마다 인스턴스 수를 카운트하도록 하세요.

기본 제공 코드:

// 테스트 케이스
const book1 = new Book('1984');
const book2 = new Book('하이퍼리얼리티');
console.log(Book.getCount()); // 2 

문제풀이:

class Book {
  static count = 0;
  constructor(title) {
    this.title = title;
    Book.count++;
  }
  static getCount() {
    return this.count;
  }
}
const book1 = new Book("1984");
const book2 = new Book("하이퍼리얼리티");
console.log(Book.getCount()); // 2

✅ 24.10.31 (목)

아예 못 풀었음, 
`static`을 다 넣어야 하는지 
`count` 초기화를 어디에 하는지 감을 못 잡았음

10. 기본값 설정

문제 10: User 클래스를 정의하고, age의 기본값을 18로 설정하도록 하세요.

기본 제공 코드:

// 테스트 케이스
const user = new User('홍길동');
console.log(user.info()); // 홍길동의 나이는 18세입니다.

문제풀이:

class User {
  constructor(name) {
    this.name = name;
    this.age = 18;
  }
  info() {
    return `${this.name}의 나이는 ${this.age}입니다`;
  }
}
const user = new User("홍길동");
console.log(user.info()); // 홍길동의 나이는 18세입니다.

할인율 계산기 클래스

문제: 할인율 계산 클래스 구현

DiscountCalculator 클래스를 사용하여 주어진 원래 가격과 할인율을 기반으로 최종 가격과 할인 금액을 계산하는 기능을 구현하였습니다. 이 클래스는 다음과 같은 속성과 메서드를 포함합니다:

  • 속성:
    • _originalPrice: 원래 가격 (0 이상의 값)
    • _discountRate: 할인율 (0에서 100 사이의 값)
  • 메서드:
    • finalPrice: 할인 적용 후 최종 가격을 계산하여 반환하는 getter
    • discountAmount: 할인 금액을 계산하여 반환하는 getter
    • originalPrice: 원래 가격을 설정하는 setter (음수일 경우 0으로 설정)
    • discountRate: 할인율을 설정하는 setter (0보다 작으면 0, 100보다 크면 100으로 설정)

질문:

  1. DiscountCalculator 클래스의 각 속성과 메서드의 기능을 구현하세요

기본 제공 코드:

const calculator = new DiscountCalculator(100, 20);
console.log(`Original Price: $${calculator._originalPrice}`); // 100
console.log(`Discount Rate: ${calculator._discountRate}%`);   // 20
console.log(`Discount Amount: $${calculator.discountAmount}`); // 20
console.log(`Final Price: $${calculator.finalPrice}`);         // 80
calculator.discountRate = 30;
console.log(`Updated Discount Rate: ${calculator._discountRate}%`); // 30
console.log(`Updated Final Price: $${calculator.finalPrice}`);       // 70

문제풀이:

class DiscountCalculator {
  constructor(originalPrice, discountRate) {
    this._originalPrice = originalPrice;
    this._discountRate = discountRate;
  }
  set originalPrice(value) {
    this._originalPrice = value > 0 ? value : 0;
  }
  set discountRate(value) {
    if (value < 0) {
      this._discountRate = 0;
    } else if (value > 100) {
      this._discountRate = 100;
    } else {
      this._discountRate = value;
    }
  }
  get discountAmount() {
    return this._originalPrice * this._discountRate * 0.01;
  }
  get finalPrice() {
    return (
      this._originalPrice - this._originalPrice * this._discountRate * 0.01
    );
  }
}
const calculator = new DiscountCalculator(100, 20);
console.log(`Original Price: $${calculator._originalPrice}`); // 100
console.log(`Discount Rate: ${calculator._discountRate}%`); // 20
console.log(`Discount Amount: $${calculator.discountAmount}`); // 20
console.log(`Final Price: $${calculator.finalPrice}`); // 80
calculator.discountRate = 30;
console.log(`Updated Discount Rate: ${calculator._discountRate}%`); // 30
console.log(`Updated Final Price: $${calculator.finalPrice}`); // 70

✅ 24.10.31 (목)

ser discountRate 안에 if문 넣지 않았음
profile
첫 시작!

0개의 댓글