logo CodeStepByStep logo

initializeName

Language/Type: JavaScript json objects
Author: Melissa Hovik (on 2018/10/22)

Write a function named initializeName that takes as a parameter a JavaScript object representing name data in the following format:

{
    "first" : "FIRSTNAME",
    "middle": "MIDDLENAME (optional)",
    "last"  : "LASTNAME"
}

and returns a string representation of the name's initials in the format "F.M.L." where "F" is the capitalized first letter of the first name, "M" is the capitalized first letter of the middle name, and "L" is the capitalized letter of the last name. If there is no "middle" name key for the passed object or if the value for the key is the empty string, the returned string should instead be in the format "F.L.".

For example, for the following variable:

let fullNameData = {
    "first" : "foo",
    "middle": "mumble",
    "last"  : "bar"
}

the call initializeName(fullNameData) should return "F.M.B.". For the following variable (without a middle name):

let partialNameData = {
    "first" : "Mowgli",
    "last" : "Hovik"
}

the call initializeName(partialNameData) should return "M.H.".

You may assume that the passed object is non-null and that values for "first", "middle", and "last" will always be of the string type, but if missing either of the required "first" or "last" keys your function should throw an exception with the message, "Passed object must have keys of 'first' and 'last'".

If instead either "first" or "last" values are empty strings, your function should throw an exception with the message, "Each name part must have a non-empty string value".

Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.