Created
March 19, 2017 02:53
-
-
Save patrickskim/2f1439a4680fd70f1a38052eb15898cf to your computer and use it in GitHub Desktop.
Simple Templating interview question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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