Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template and Place holders algorithm

First a quick definition :)

  • Template - A string which may contain placeholders (example:"hello [name]")
  • Placeholder - A substring whitin square brackets (example: "name" in "hello [name]:).
  • Properties map - A valid object with strings as values

I need to write a code that replace placeholders (along with brackets) with the matching values in the properties map.

example: for the following properties map:

{
    "name":"world",
    "my":"beautiful",
    "a":"[b]",
    "b":"c",
    "c":"my"
}

Expected results:

  • "hello name" -> "hello name"

  • "hello [name]" -> "hello world"

  • "[b]" -> "c"

  • "[a]" -> "c" (because [a]->[b]->[c])

  • "[[b]]" -> "my" (because [[b]]->[c]->my)

  • "hello [my] [name]" -> "hello beautiful world"

like image 640
Shlomi Schwartz Avatar asked Oct 19 '25 01:10

Shlomi Schwartz


1 Answers

var map = {
    "name":"world",
    "my":"beautiful",
    "a":"[b]",
    "b":"c",
    "c":"my"
};

var str = "hello [my] [name] [[b]]";

do {
    var strBeforeReplace = str;
    for (var k in map) {
        if (!map.hasOwnProperty(k)) continue;
        var needle = "[" + k + "]";
        str = str.replace(needle, map[k]);
    }
    var strChanged = str !== strBeforeReplace;
} while (strChanged);

document.write(str); //hello beautiful world my
like image 145
goat Avatar answered Oct 21 '25 14:10

goat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!