Typescript/러닝 타입스크립트 연습문제

(1장) The Typeinator - 2. Prototypes to Classes

띵킹 2023. 4. 5. 21:21

https://github.com/LearningTypeScript/projects/tree/main//projects/from-javascript-to-typescript/the-typeinator/02-prototypes-to-classes

 

GitHub - LearningTypeScript/projects: Hands-on real world projects that will help you exercise your knowledge of TypeScript.

Hands-on real world projects that will help you exercise your knowledge of TypeScript. - GitHub - LearningTypeScript/projects: Hands-on real world projects that will help you exercise your knowledg...

github.com

점검해야 할 다음 프로젝트는 클래스 문법 이전부터 시작됩니다. 얼마나 원시적입니까?

original.js 파일에는 클래스로 사용되는 로봇 및 휴머노이드 기능에 대한 프로젝트의 원본 코드가 포함되어 있습니다. 귀하의 임무는 해당 코드를 적절한 ES2015+ class 문법으로 이식하는 것입니다.

## 명세

`index.js`에서 ES2015 `class` 문법을 사용하여 두 클래스를 내보냅니다.

- `original.js`의 `Robot` 기능을 기반으로 하는 `Robot`
- `original.js`의 `Humanoid` 기능을 기반으로 `Robot` 클래스를 확장한 `Humanoid`

## 파일

- `index.js`: 여기에 `Robot` 및 `Humanoid` 기능을 작성합니다.
- `index.test.js`: `Robot` 및 `Humanoid` 검증 테스트
- `solution.js`: 솔루션 코드

 

함수와 프로토타입으로 정의된 예전 방식의 객체지향 코드를 클래스 문법 형태로 수정하는 간단한 문제.

class Robot {
	constructor(name, abilities) {
		this.name = name;
		this.abilities = abilities;
		this.power = 100;
	}
	announce() {
		console.log("Greetings. I am " + this.name + ".");
		for (var i = 0; i < this.abilities.length; i += 1) {
			console.log("I am able to " + this.abilities[i] + ".");
		}
	}
	charge(amount) {
		if (this.power < 100) {
			this.power = Math.min(this.power + amount, 100);
			console.log("Recharged power supplies to " + this.power + ".");
		}

		if (this.power === 100) {
			console.log("I am at optimal operational capacity.");
		}
	}
	move(distance) {
		if (this.power < distance) {
			console.log("I do not have enough power to move " + distance + " units.");
		} else {
			console.log("Moving " + distance + " units.");
			this.power -= distance;
		}
	}
}

class Humanoid extends Robot {
	constructor(name, abilities, catchphrase) {
		super(name, abilities);
		this.catchphrase = catchphrase;
	}
	announce() {
		super.announce();
		console.log(" > " + this.catchphrase + " <");
	}
}

module.exports.Humanoid = Humanoid;
module.exports.Robot = Robot;

메소드의 내부 구현은 복사 붙여넣기 했다.

 

 

728x90