Skip to content

Instantly share code, notes, and snippets.

@patrickskim
Created March 19, 2017 02:53
Show Gist options
  • Save patrickskim/2f1439a4680fd70f1a38052eb15898cf to your computer and use it in GitHub Desktop.
Save patrickskim/2f1439a4680fd70f1a38052eb15898cf to your computer and use it in GitHub Desktop.
Simple Templating interview question
class TemplateEngine {
constructor(stringTemplate) {
this.template = stringTemplate;
}
format(props) {
let chunks = this.template.split('<%');
let interped = '';
chunks.forEach((chunk) => {
let subChunk = chunk.split('%>');
if (subChunk.length > 1) {
subChunk[0] = props[subChunk[0]] || '';
interped += subChunk.join('');
} else {
interped += subChunk[0];
};
});
return interped;
}
}
const temp = '<p>hello this is a template named: <%name%>,\n <%greetings%> <%friendName%></p>';
const props = {
name: "Pique",
greetings: "wassup",
friendName: "gin",
};
const prop2s = {
name: "Pique",
};
const tempEngine = new TemplateEngine(temp);
console.log(tempEngine.format(prop2s));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment