Skip to content
This repository was archived by the owner on Oct 1, 2025. It is now read-only.

Commit 3b8f410

Browse files
committed
feat: Coding Challenge 2 of OOP Section Done
1 parent a4e4daa commit 3b8f410

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

challenges/section14-challenges.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,77 @@ for (let j = 0; j < 3; j++)
5252

5353
for (let k = 0; k < 4; k++)
5454
car1.brake();
55+
56+
// Coding Challenge 2
57+
58+
/*
59+
1. Re-create Challenge #1, but this time using an ES6 class (call it 'CarCl')
60+
2. Add a getter called 'speedUS' which returns the current speed in mi/h (divide
61+
by 1.6)
62+
3. Add a setter called 'speedUS' which sets the current speed in mi/h (but
63+
converts it to km/h before storing the value, by multiplying the input by 1.6)
64+
4. Create a new car and experiment with the 'accelerate' and 'brake'
65+
methods, and with the getter and setter.
66+
Test data:
67+
§ Data car 1: 'Ford' going at 120 km/h
68+
*/
69+
70+
class CarCl
71+
{
72+
constructor (make, speed)
73+
{
74+
this.make = make;
75+
this.speed = speed;
76+
}
77+
78+
get speedUs ()
79+
{
80+
return this.speed / 1.6;
81+
}
82+
83+
set speedUs (miPerHour)
84+
{
85+
this.speed = miPerHour * 1.6;
86+
}
87+
88+
logSpeed ()
89+
{
90+
console.log(`${ this.make } going at ${ this.speed } km/h`);
91+
}
92+
93+
logSpeedUS ()
94+
{
95+
console.log(`${ this.make } going at ${ this.speedUs } mi/h`);
96+
}
97+
98+
accelerate ()
99+
{
100+
this.speed += 10;
101+
this.logSpeed();
102+
}
103+
104+
brake ()
105+
{
106+
this.speed -= 5;
107+
this.logSpeed();
108+
}
109+
}
110+
111+
const car3 = new CarCl('Ford', 120);
112+
113+
car3.logSpeed();
114+
car3.logSpeedUS();
115+
116+
for (let j = 0; j < 3; j++)
117+
car3.accelerate();
118+
119+
car3.logSpeedUS();
120+
121+
for (let k = 0; k < 4; k++)
122+
car3.brake();
123+
124+
car3.logSpeedUS();
125+
126+
car3.speedUs = 200;
127+
car3.logSpeedUS();
128+
car3.logSpeed();

0 commit comments

Comments
 (0)