Last active
March 4, 2017 22:45
-
-
Save krazov/14024d2012e5073506ed87cdd57daa37 to your computer and use it in GitHub Desktop.
String transformation with `reduce()`
This file contains 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
// 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