Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a Simple Dynamic Site with Node.js Creating a Basic Template Engine in Node.js A Simple Merge Utility

Hi I am totally lost on this code challenge, someone please go step by step with detailed explanations

I am totally stumped please see title of my question

index.js
var utilities = require("./utilities");

var mailValues = {};

mailValues.first_name = "Janet";

var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";

var mergedContent = utilities.merge(emailTemplate, mailValues);

//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
utilities.js
function merge(content, values) {

  return content;
}


module.exports.merge = merge;

1 Answer

Damien Watson
Damien Watson
27,419 Points

Hi, I'll do the best I can to explain this for you.

The 'index.js' file doesn't need to be changed but I will break it down:

index.js
var utilities = require("./utilities");

// Create mailValues object
var mailValues = {};

// Add 'first_name'  to mailValues object
// mailValues = { first_name: "Janet" }
mailValues.first_name = "Janet";

// Content has the 'first_name' surrounded by '%' to differentiate items to be replaced
var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";

// Pass both of these items into the utility
var mergedContent = utilities.merge(emailTemplate, mailValues);

//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
utilities.js
function merge(content, values) {

  // Loop through all values and replace the place holder with the associated content
  // values == { first_name : "Janet" }
  // So the loop below would do:
  // content = content.replace("%first_name%", "Janet");
  for (var key in values) {
    content = content.replace("%"+key+"%", values[key]);
  }

  return content;
}

module.exports.merge = merge;

Thank you so much for assisting me with this, your solution albeit a little modified worked perfectly!