FreeCodeCamp and JavaScript: Make a Person

So as I mentioned, I’ve already finished the other FreeCodeCamp Advanced Algorithms.  Right now I need to complete the Simon game in order to get my Front End Certificate.  I hope to do that this week, but in the meantime, I may go over some of the rest of the challenges.  Here’s the next one, “Make a Person“.

So, here are the instructions:

Fill in the object constructor with the following methods below:

getFirstName()
getLastName()
getFullName()
setFirstName(first)
setLastName(last)

setFullName(firstAndLast)

Run the tests to see the expected output for each method.

The methods that take an argument must accept only one argument and it has to be a string.

These methods must be the only available means of interacting with the object.

For hints, FreeCodeCamp gives us:

Here are some helpful links:

Finally, the starter code:

var Person = function(firstAndLast) {
    return firstAndLast;
};
var bob = new Person(‘Bob Ross’);

bob.getFullName();

I have to admit that this one was pretty easy for me, since I have a Java course under my belt, which had already introduced me to set() and get() methods.  These allow you to set the properties individually, since you cannot access the actual variables themselves.  You send your value to these methods and they store the value inside the function.  You can read about this at the link on closures above.

So, I take the input and break it apart, assigning the elements of the array to the various corresponding methods.  I have three set methods and three get methods, as per the instructions. The various tests call the different methods, and the values change with the calls.  So, here’s my solution; feel free to ask questions in the comments.

var Person = function(firstAndLast) {
    var name = firstAndLast.split(‘ ‘);
    firstName = name[0];
    lastName = name[1];
    var fullName = firstAndLast;
    this.getFirstName = function() {
        return firstName;
    };
    this.getLastName = function() {
        return lastName;
    };
    this.setFirstName = function(first) {
        firstName = first;
    };
    this.setLastName = function(last) {
        lastName = last;
    };
    this.setFullName = function(firstAndLast) {
        fullName = firstAndLast;
    };
    this.getFullName = function() {
        return firstName + ” ” + lastName;
    };
    return firstAndLast;
};
var bob = new Person(‘Bob Ross’);
bob.getFullName();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s