JavaScript: Building a fitness app - data and models (Article) | JavaScriptSource

JavaScript: Building a fitness app - data and models (Article)

JavaScriptSource Staff Mar 14, 2016

By John R. Larsen

This article was excerpted from the book Get Programming with JavaScript.

Your development work has really got you noticed (The Fruitinator! was a global smash) and you’re now part of a team developing a fitness application. Health-conscious users track their exercise, logging the date and duration of each session.

       Mahesha
       35 minutes on February 5th, 2017
       45 minutes on February 6th, 2017

       1 hour 20 minutes so far.
       Great work!

The team is working on an Android version of the app using the Python programming language, an iOS version using Swift and a web-based version using JavaScript. The same data will be used in all versions (figure 1).

same data is used
Figure 1: The same data is used by the different versions of the app

Tasks involved in building the app include

  1. Retrieve user data as a string
  2. Convert user data into user models
  3. Display user data
  4. Provide an interface for users to add sessions

The data is transferred across the internet as text. The format of the text is JSON (JavaScript Object Notation. The text is very easy to convert into a JavaScript object. The team has asked you to concentrate on the second task, building user models from user data.

Defining a User constructor

You've been asked to write some JavaScript code to model a fitness app user. Your model needs to do the following:

  1. Store the user’s name.
  2. Store a list of exercise sessions for the user, each with a date and duration.
  3. Include a method for adding sessions to the list.
  4. Include a method for retrieving data about the user.

Listing 1 shows your initial constructor function. You test it on the console:

    > var user = new User("Mahesha")
      undefined
    > user.addSession("2017-02-05", 120)
      120
    > user.addSession("2017-02-06", 35)
      155
    > user.getData().total
      155

Listing 1 The User constructor

var User = function (name) {

    var sessions = [];                                               #A
    var totalDuration = 0;                                           #A

    this.addSession = function (sessionDate, duration) {

        sessions.push({                                              #B
            "sessionDate" : sessionDate,                             #B
            "duration"    : duration                                 #B
        });                                                          #B

        totalDuration += duration;                                   #C

        return totalDuration;
    };
  
    this.getData = function () {                                     #D
        return {
            "name"    : name,
            "total"   : totalDuration,
            "sessions": sessions.slice()                             #E
        };
    };
};

#A Declare private variables
#B Add a session object to the sessions array
#C Add the current session’s duration to the total
#D Define a function to retrieve user data
#E Use slice to copy the sessions array

 

The constructor includes a name parameter, some private variables declared using var and two public methods assigned to the this object, addSession and getData. The getData method uses slice with no arguments to grab a copy of the sessions array. Providing a copy of the session information prevents users from tweaking the sessions array outside of the addSession method.

When you create a JavaScript object using the User constructor, you have created a user model. The model is more than just data; it includes private variables and public methods for managing the data, as shown in figure 2.

user model

Figure 2: A user model created by the User constructor function

If the model is more than the data, what does the data look like?

Getting a feel for the data as a JavaScript object

The data for a user is a simple JavaScript object:

var userData = {
    "name" : "Mahesha",
    "sessions" : [
        { "sessionDate" : "2017-02-05", "duration" : 120 },
        { "sessionDate" : "2017-02-06", "duration" : 35 },
        { "sessionDate" : "2017-02-06", "duration" : 45 }
    ]
};

You can access its properties, like dataObject.name. But it’s still just data; it doesn’t have the extra capabilities of a model built with the User constructer, like an addSession or getData method. The data object is shown again in figure 3 for comparison with figure 2.

User data represented

Figure 3 User data represented as a simple JavaScript object

In order to make the most of the extra methods provided by a user model, you need to define a function to build a model from the basic data object.

Converting the data into a user model

In listing 3, you define the buildUser function that takes data for a single user as a JavaScript object and creates a model by calling the User constructor. You test the buildUser function by creating a user model with it from a JavaScript object. Adding one extra exercise session for the created user produces the following output on the console:

> 240

You are using the User constructor from listing 1 so you import that by adding an HTML script element to the project, as shown first in listing 2.

[JS Bin Listings 14.02 & 14.03] (http://jsbin.com/zenire/edit?html,js,console)

Listing 2 A function to build a user model from user data (HTML)

<!-- User constructor -->
<script src="http://output.jsbin.com/suzala.js"></script>

 

[JS Bin Listings 14.02 & 14.03] (http://jsbin.com/zenire/edit?html,js,console)

Listing 3 A function to build a user model from user data

var buildUser = function (userData) {

  var user = new User(userData.name);                                  #A
  
  userData.sessions.forEach(function (sesh) {
    user.addSession(sesh.sessionDate, sesh.duration);                  #B
  });
  
  return user;                                                         #C
};


var userData = {                                                       #D
  "name" : "Mahesha",                                                  #D
  "sessions" : [                                                       #D
    {"sessionDate": "2017-02-05", "duration": 120},                    #D
    {"sessionDate": "2017-02-06", "duration": 35},                     #D
    {"sessionDate": "2017-02-06", "duration": 45}                      #D
  ]                                                                    #D
};                                                                     #D

var user = buildUser(userData);                                        #E

console.log(user.addSession("2017-02-15", 40));                        #F

#A Create a new user object with the User constructor
#B Add each session
#C Return the newly created user model
#D Create a JavaScript object to hold the user data
#E Call buildUser to create a model from the data
#F Add a session and log the total time returned

 

With the buildUser function you can now upgrade plain user data, stored as a simple JavaScript object, to an enhanced user model that hides the data as private variables but adds methods to manage the state of the model and access a copy of the data.

What's next for the fitness app?

Your team is pleased with your work on the app; you've fulfilled the initial requirements. The full set of requirements for the app is repeated below.

  1. Retrieve user data as a string
  2. Convert user data into user models
  3. Display user data
  4. Provide an interface for users to add sessions

You've completed the second requirement.

cover

JavaScript: Building a fitness app - data and models

By John R. Larsen
This article was excerpted from the book Get Programming with JavaScript.

Leave a Response

(0 comments)