String Interpolation with a Missing-Value Mode
Problem statement
Write a small string-interpolation function, similar to JavaScript template strings. A placeholder is ${name}, where name starts with a letter or _ and continues with letters, digits, or _. Names are case-sensitive. The value of names[i] is values[i].
Scan text from left to right and build the result:
- A backslash followed by
$or by another backslash outputs that second character, and both characters are used up. Any other backslash is copied as is. ${starts a placeholder that ends at the next}. If there is no later}, or the characters between the braces are not a valid name, the placeholder is malformed.- A placeholder whose name has a value is replaced by that value. The value is inserted as is and is never scanned again.
- A placeholder whose name has no value depends on
mode:"error"stops with an error,"keep"keeps the placeholder text unchanged, and"empty"replaces it with nothing. - Every other character, including a
$that is not followed by{, is copied as is.
Return the finished string. If the scan stops with an error, return only the error for the first problem found: "ERROR: malformed placeholder at i", where i is the 0-based index of the placeholder's $ in text, or "ERROR: missing value for name" with the placeholder's name. A malformed placeholder is an error in every mode.
Function
interpolate(text: String, names: String[], values: String[], mode: String) → StringExamples
Example 1
text = "Hello, ${name}! You have ${count} new messages."names = ["name", "count"]values = ["Ana", "3"]mode = "error"return = "Hello, Ana! You have 3 new messages."Both placeholders have values, so ${name} becomes Ana and ${count} becomes 3. The rest of the text is copied as is.
Example 2
text = "Price \\${cost} is ${cost} for ${user}"names = ["cost"]values = ["$5"]mode = "keep"return = "Price ${cost} is $5 for ${user}"The backslash makes \$ a plain $, so the first ${cost} is ordinary text. The second ${cost} becomes $5; that value is not scanned again. user has no value, and in keep mode ${user} stays as it was.
Example 3
text = "${greeting}, ${who}"names = ["greeting"]values = ["Hi"]mode = "error"return = "ERROR: missing value for who"${greeting} has a value, but ${who} does not. In error mode the result is the error string for the first placeholder without a value.
Example 4
text = "a ${x} b ${y} c ${"names = ["x"]values = ["1"]mode = "empty"return = "ERROR: malformed placeholder at 16"In empty mode ${y} would be removed, but the ${ that starts at index 16 is never closed. A malformed placeholder is an error in every mode.
Constraints
0 <= text.length <= 20000 <= names.length <= 100values.length == names.length1 <= names[i].length <= 300 <= values[i].length <= 20textand everyvalues[i]contain only printable ASCII characters (codes 32 to 126).- Every
names[i]is a valid name, and the names are distinct. modeis"error","keep", or"empty".