Skip to content

Instantly share code, notes, and snippets.

@krazov
Last active March 4, 2017 22:45
Show Gist options
  • Save krazov/14024d2012e5073506ed87cdd57daa37 to your computer and use it in GitHub Desktop.
Save krazov/14024d2012e5073506ed87cdd57daa37 to your computer and use it in GitHub Desktop.
String transformation with `reduce()`
// mocked stuff
const stringTemplate = 'I’m sorry, {astronautName}. I’m afraid I can’t do that. This mission is too important for me to allow you to {unwantedThing} it.';
const values = {
astronautName: 'Dave',
unwantedThing: 'jeopardize'
};
// original function
function parseTemplate(stringTemplate, values) {
for (var key in values) {
if (values.hasOwnProperty(key)) {
stringTemplate = stringTemplate.replace(new RegExp('{' + key + '}', 'g'), values[key]);
}
}
return stringTemplate;
}
// new function
// mind you, it happened in ES5 environment so no arrow functions this time
function parseTemplateFP(stringTemplate, values) {
return Object.keys(values).reduce(function (string, key) {
return string.replace(new RegExp('{' + key + '}', 'g'), values[key]);
}, stringTemplate);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment