본문 바로가기

1일1알고리즘

Grasshopper - Create the rooms, 객체, 생성자 함수와 상속 | Codewars [자바스크립트]

Codewars 8kyu 문제 Grasshopper - Create the rooms.

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

객체에 방을 3개 담되 각 방마다 프라퍼티가 3개 이상 있어야 함.

 

처음엔 단순하게 만들어봄.

const rooms = {
  room1: {
    name: "Room1",
    description: "This is the first room.",
    completed: true
  },
  
  room2: {
    name: "Room2",
    description: "This is the second room.",
    completed: false
  },
  
  room3: {
    name: "Room3",
    description: "This is the third room.",
    completed: true
  }
}

 

그러고 나서 생성자 함수 배운 걸 써먹어보고 싶어짐.

그래서 내용 찾아보면서 코드 다시 써봄.

const Room = function(name, description, completed) {
  this.name = name;
  this.description = description;
  this.completed = completed;
}

const rooms = {
  room1: new Room('Room1', 'This is the first room.', true),
  room2: new Room('Room2', 'This is the second room.', false),
  room3: new Room('Room3', 'This is the third room.', true)
}

생성자 함수를 만든다. new를 이용해서 빈 객체를 생성한다. new로 부른 함수는 this가 global이 아닌 해당 변수를 가리킨다.

 

당장 효율성 차이는 별로 없을 듯. 다만 만들어야 하는 방 개수가 많아지면 생성자 함수를 반복해서 사용하는 게 효율적일 수도.

 

그리고 혼자 조금 응용해봄.

const Room = function(name, description, completed) {
  this.name = name;
  this.description = description;
  this.completed = completed;
}

Room.prototype.sinceConstructed = function(constructionYear) {
  return 2020 - constructionYear;
};

const rooms = {
  room1: new Room('Room1', 'This is the first room.', true),
  room2: new Room('Room2', 'This is the second room.', false),
  room3: new Room('Room3', 'This is the third room.', true)
}

console.log(rooms.room1); 
/* Room {
     name: 'Room1',
     description: 'This is the first room.',
     completed: true
   } */

console.log(rooms.room1.sinceConstructed(2000)); // 20