Last active
April 17, 2020 00:06
-
-
Save BicanMarianValeriu/af0aeac7624dcd56d929724ef35b97ea to your computer and use it in GitHub Desktop.
Fanciest Variable Mapping over a string
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
const variables = { | |
name: 'Bican Marian Valeriu', | |
job: 'WordPress Developer', | |
}; | |
const destruct = (obj, ...keys) => keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {}); | |
const mapVariables = (variables, string) => { | |
let rxp = /{{([^}]+)}}/g, curMatch; | |
while (curMatch = rxp.exec(string)) { | |
const trimd = curMatch[1].trim(); | |
const found = destruct(variables, trimd); | |
if (found[trimd] === undefined) continue; | |
string = string.replace(new RegExp(`{{${curMatch[1]}}}`, 'g'), found[trimd]); | |
} | |
return string; | |
}; | |
const output = mapVariables(variables, '{{ name }} is a {{job}} at MyZone Media.' ); | |
console.log( output ); | |
// Output if all vars are found | |
// Bican Marian Valeriu is a WordPress Developer at MyZone Media. | |
// Output if just some of the vars are found | |
// Bican Marian Valeriu is a {{job}} at MyZone Media. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment