ES2015 Classes & Static Methods - Exercise

Contact Us or call 1-877-932-8228
ES2015 Classes & Static Methods - Exercise

ES2015 Classes & Static Methods

Duration: 15 to 25 minutes.

In this exercise, you will rewrite our Vehicle/Fleet code using ES2015 classes, and add a static method.

  1. Open AdvancedObjects/Exercises/vehiclesclasses.html for editing.
  2. Where indicated by the comments, complete class Vehicle:
    • Add a constructor
    • Add a toString() method
    • Write static method Compare(v1, v2) to compare two Vehicles, returning 1, -1, or 0, as defined in the comments
  3. Where indicated by the comments, complete class Fleet:
    • Add a constructor
    • Add method addVehicle(vehicle)
    • Add method toString()
    • Method averageAgeOfVehicles() is done for you
  4. The HTML markup and event-handling code is done for you. The page now includes a form, presented to users when there are at least two vehicles in the fleet, to be used to compare any two vehicles. Write code to invoke method Compare(v1, v2) and send the result in an message.
  5. Test your solution in a browser.

Solution:

AdvancedObjects/Solutions/vehiclesclasses.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Company Fleet</title>
	<style>
		form#addVehicle {
			float:left;
			width:48%;
		}
		div#info {
			float:right;
			width:48%;
		}
		form#compare {
			margin-top:15px;
		}
	</style>
	<script>
		class Vehicle {
			constructor(vehicleType, yearPurchased, VIN, purchasePrice) {
				this.vehicleType = vehicleType;
				this.yearPurchased = yearPurchased;
				this.VIN = VIN; //vehicle identification number
				this.purchasePrice = purchasePrice.replace(/\$/g,'');
			}
			toString() {
				return this.yearPurchased + ' ' + this.vehicleType + ', $' + parseInt(this.purchasePrice).formatMoney(0) + ' VIN: ' + this.VIN;
			}
			static Compare(v1, v2) {
				if (v1.purchasePrice !== v2.purchasePrice) {
					if (v1 < v2) {
						return 1;
					} else {
						return -1;
					}
				} else if (v1.yearPurchased !== v2.yearPurchased) {
					if (v1.yearPurchased > v2.yearPurchased) {
						return 1;
					} else {
						return -1;
					}
				}
				return 0;
			}
		}

		class Fleet {
			constructor(companyName) {
				this.companyName = companyName;
				this.vehicles = [];
			}
			addVehicle(vehicle) {
				this.vehicles.push(vehicle);
			}
			toString() {
				var str = 'Current fleet for <strong>' + this.companyName + '</strong>:';
				str += '<ul>';
				for (let v in this.vehicles) {
					if (this.vehicles.hasOwnProperty(v)) {
						let vehicle = this.vehicles[v];
						str += '<li><strong>' + v + '</strong>: ' + vehicle + '</li>';
					}
				}
				str += '</ul>';
				return str;
			}
			averageAgeOfVehicles() {
				if (this.vehicles.length === 0) {
					return 0;
				}
				var yearSum = 0;
				for (let v in this.vehicles) {
					if (this.vehicles.hasOwnProperty(v)) {
						let vehicle = this.vehicles[v];
						yearSum += parseInt(vehicle.yearPurchased);
					}
				}
				var averageYear = parseInt(yearSum / this.vehicles.length);
				var curYear = new Date().getFullYear();
				return curYear - averageYear;
			}
		}

		Number.prototype.formatMoney = function(c, d, t) {
			var n = this, 
				c = isNaN(c = Math.abs(c)) ? 2 : c, 
				d = d == undefined ? "." : d, 
				t = t == undefined ? "," : t, 
				s = n < 0 ? "-" : "", 
				i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
				j = (j = i.length) > 3 ? j % 3 : 0;
					return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
		 };

		function clearFields() {
			document.getElementById('vehicleType').value = '';
			document.getElementById('yearPurchased').value = '';
			document.getElementById('VIN').value = '';
			document.getElementById('purchasePrice').value = '';
		}

		window.onload = function() {
			var CompanyFleet = new Fleet('ABC, Inc.');
			document.getElementById('currentFleetInfo').innerHTML = CompanyFleet;

			var addVehicleForm = document.getElementById('addVehicle');
			addVehicleForm.addEventListener('submit',
				function(eventevent) {
					event.preventDefault();
					var vehicleType = document.getElementById('vehicleType').value;
					var yearPurchased = document.getElementById('yearPurchased').value;
					var VIN = document.getElementById('VIN').value;
					var purchasePrice = document.getElementById('purchasePrice').value;
					CompanyFleet.addVehicle(new Vehicle(vehicleType, yearPurchased, VIN, purchasePrice));
					document.getElementById('currentFleetInfo').innerHTML = CompanyFleet;
					clearFields();
					if (CompanyFleet.vehicles.length >= 2) {
						var select1 = '';
					    select1 += '<select id="v1">';
					    for (var v=0; v<CompanyFleet.vehicles.length; v++) {
							select1 += '<option value="'+v+'">Vehicle '+v+'</option>';
						}
					    select1 += '</select>';

						var select2 = '';
					    select2 += '<select id="v2">';
					    for (var v=0; v<CompanyFleet.vehicles.length; v++) {
							select2 += '<option value="'+v+'">Vehicle '+v+'</option>';
						}
					    select2 += '</select>';

					    var submitButton = '<input type="submit" value="Compare">';

					    var compareForm = document.getElementById('compare');
					    compareForm.innerHTML = select1 + ' ' + select2 + ' ' + submitButton;
					}
				},
				false);
			var getAverageAgeButton = document.getElementById('getAverageAge');
			
			getAverageAgeButton.addEventListener('click',
				function() {
					var averageAge = CompanyFleet.averageAgeOfVehicles();
					alert('The average age of all vehicles is ' + averageAge + ' years');
				},
				false);

			var compareForm = document.getElementById('compare');
			compareForm.addEventListener('submit',
				function(event) {
					event.preventDefault();
					var selectedVehicle1 = document.getElementById('v1').value;
					var selectedVehicle2 = document.getElementById('v2').value;
					var compareResult = Vehicle.Compare(CompanyFleet.vehicles[selectedVehicle1], CompanyFleet.vehicles[selectedVehicle2]);
					var msg = '';
					if (compareResult > 0) {
						msg = 'Vehicle ' + selectedVehicle1 + ' is better';
					} else if (compareResult < 0) {
						msg = 'Vehicle ' + selectedVehicle2 + ' is better';
					} else {
						msg = 'Vehicles are the same';
					}
					alert(msg);
				},
				false);
		}
	</script>
</head>
<body>
	<h1>Company Fleet</h1>
	<form id="addVehicle">
		<select id="vehicleType">
			<option value="">-vehicle type-</option>
			<option value="car">car</option>
			<option value="van">van</option>
			<option value="truck">truck</option>
			<option value="bus">bus</option>
		</select>
		<input type="text" id="yearPurchased" placeholder="year purchased">
		<br>
		<input type="text" id="VIN" placeholder="VIN">
		<input type="text" id="purchasePrice" placeholder="purchase price">
		<br>
		<input type="submit" value="Add Vehicle">
	</form>
	<div id="info">
		<div id="currentFleetInfo"></div>
		<button id="getAverageAge">Average Age of Vehicles</button>
		<form id="compare"></form>
	</div>
</body>
</html>

Code Explanation

The definitions for the classes are similar to the work we did in the previous exercise; we now use the new ES2015 class syntax.

We add static method Compare(v1, v2) to class Vehicle:

  • If the vehicles' purchase prices differ, we return 1 or -1 as appropriate;
  • Else if the vehicles' year of purchase differ, we return 1 or -1 as appropriate;
  • Otherwise, we return 0 (since the vehicles are, by this calculus, the same).

In the event handler for the user submitting the #compare form, we set variable compareResult = Vehicle.Compare(CompanyFleet.vehicles[selectedVehicle1], CompanyFleet.vehicles[selectedVehicle2]), comparing the two user-selected vehicles via the static method Compare, build a string message based on the results, and return the message to the user with an alert popup.

Next