Advertisement
kstoyanov

02. Pet House JS Advanced Exam - 27 June 2020

Sep 29th, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solveClasses() {
  2.   class Pet {
  3.     constructor(owner, name) {
  4.       this.owner = owner;
  5.       this.name = name;
  6.       this.comments = [];
  7.     }
  8.  
  9.     addComment(comment) {
  10.       if (this.comments.includes(comment)) {
  11.         throw new Error('This comment is already added!');
  12.       }
  13.  
  14.       this, this.comments.push(comment);
  15.  
  16.       return 'Comment is added.';
  17.     }
  18.  
  19.     feed() {
  20.       return `${this.name} is fed`;
  21.     }
  22.  
  23.     toString() {
  24.       const result = [];
  25.  
  26.       result.push(`Here is ${this.owner}'s pet ${this.name}.`);
  27.  
  28.      if (this.comments.length > 0) {
  29.        result.push(`Special requirements: ${this.comments.join(', ')}`);
  30.      }
  31.  
  32.      return result.join('\n');
  33.    }
  34.  }
  35.  
  36.  class Cat extends Pet {
  37.    constructor(owner, name, insideHabits, scratching) {
  38.      super(owner, name);
  39.      this.insideHabits = insideHabits;
  40.      this.scratching = scratching;
  41.    }
  42.  
  43.    feed() {
  44.      return `${super.feed()}, happy and purring.`;
  45.    }
  46.  
  47.    toString() {
  48.      const result = [];
  49.  
  50.      result.push(super.toString());
  51.      result.push('Main information:');
  52.  
  53.      let tempResult = `${this.name} is a cat with ${this.insideHabits}`;
  54.  
  55.      if (this.scratching) {
  56.        tempResult += ', but beware of scratches.';
  57.      }
  58.  
  59.      result.push(tempResult);
  60.  
  61.      return result.join('\n');
  62.    }
  63.  }
  64.  
  65.  class Dog extends Pet {
  66.    constructor(owner, name, runningNeeds, trainability) {
  67.      super(owner, name);
  68.      this.runningNeeds = runningNeeds;
  69.      this.trainability = trainability;
  70.    }
  71.  
  72.    feed() {
  73.      return `${super.feed()}, happy and wagging tail.`;
  74.    }
  75.  
  76.    toString() {
  77.      const result = [];
  78.  
  79.      result.push(super.toString());
  80.      result.push('Main information:');
  81.      result.push(`${this.name} is a dog with need of ${this.runningNeeds}km running every day and ${this.trainability} trainability.`);
  82.  
  83.      return result.join('\n');
  84.    }
  85.  }
  86.  
  87.  return {
  88.    Pet,
  89.    Cat,
  90.    Dog,
  91.  };
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement