From 381a3ab65b507ca18c2ad4c75fb7ad5897bd4dd5 Mon Sep 17 00:00:00 2001 From: Amine El Baghdadi <75886237+NoobJsPerson@users.noreply.github.com> Date: Sat, 15 May 2021 17:56:31 +0000 Subject: update interpolate.js --- interpolate.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/interpolate.js b/interpolate.js index e69de29..36cf2f8 100644 --- a/interpolate.js +++ b/interpolate.js @@ -0,0 +1,13 @@ +const regex = /\${[^{]+}/g; + +export default function interpolate(template, variables, fallback) { + return template.replace(regex, (match) => { + const path = match.slice(2, -1).trim(); + return getObjPath(path, variables, fallback); + }); +} + +//get the specified property or nested property of an object +function getObjPath(path, obj, fallback = '') { + return path.split('.').reduce((res, key) => res[key] || fallback, obj); +} \ No newline at end of file -- cgit v1.2.3