Listing 15.01 - A simple user view
JS Bin
// User constructor
var User = function (name) {
var sessions = [];
var totalDuration = 0;
this.addSession = function (sessionDate, duration) {
sessions.push({
"sessionDate" : sessionDate,
"duration" : duration
});
totalDuration += duration;
return totalDuration;
};
this.getData = function () {
return {
"name" : name,
"total" : totalDuration,
"sessions": sessions.slice()
};
};
};
// View
var userView = (function () {
var getInfo = function (userData) {
var infoString = "\n" + userData.name + "\n";
userData.sessions.forEach(function (session) {
infoString += session.duration + " minutes on ";
infoString += session.sessionDate + "\n";
});
infoString += "\n" + userData.total + " minutes so far";
infoString += "\nWell done!\n";
return infoString;
};
var render = function (user) {
console.log(getInfo(user.getData()));
};
return {
render: render
};
})();
// Test
var user = new User("Mahesha");
user.addSession("2017-02-05", 35);
user.addSession("2017-02-06", 45);
userView.render(user);
Listing 15.01 - A simple user view - Task 1
- Update the view so that it displays different messages depending on the total exercise the user has completed.
var userView = (function () {
var getMessage = function (total) {
if (total > 200) {
return "Outstanding!";
}
if (total > 100) {
return "Good work!";
}
if (total > 50) {
return "Good start!";
}
if (total > 0) {
return "Not bad!";
}
return "Get going!";
};
var getInfo = function (userData) {
var infoString = "\n" + userData.name + "\n";
userData.sessions.forEach(function (session) {
infoString += session.duration + " minutes on ";
infoString += session.sessionDate + "\n";
});
infoString += "\n" + userData.total + " minutes so far";
infoString += "\n" + getMessage(userData.total) + "\n";
return infoString;
};
var render = function (user) {
console.log(getInfo(user.getData()));
};
return {
render: render
};
})();