UNPKG

@zohodesk/utils

Version:

DOT Utils Collection

77 lines (59 loc) 3.15 kB
export default function createTemplateLiteral(templateStrings) { for (var _len = arguments.length, expressionKeys = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { expressionKeys[_key - 1] = arguments[_key]; } return function () { for (var _len2 = arguments.length, expressionValues = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { expressionValues[_key2] = arguments[_key2]; } let resultString = [templateStrings[0]]; expressionKeys.forEach(function (expressionKey, i) { let expressionValue = expressionValues[i]; let nextTemplateString = templateStrings[i + 1]; if (expressionValue === null || expressionValue === undefined || expressionValue === "") { nextTemplateString = nextTemplateString.replace(/^_/, ''); } resultString.push(expressionValue, nextTemplateString); }); let resultStr = resultString.join(''); resultStr = resultStr.replace(/_$/, ''); return resultStr; }; } /* refer the doc https://developers.google.com/web/updates/2015/01/ES6-Template-Strings UnderSatnd the terms - String interpolation, Embedded expressions Go through the topic https://developers.google.com/web/updates/2015/01/ES6-Template-Strings#tagged_templates Things to note fn`Hello ${you}! You're looking ${adjective} today!` desugars to fn(["Hello ", "! You're looking ", " today!"], you, adjective); Please go through the example code Our implementation constructCustomMessage is the handler for the tagged template function. It receives the static words and its substitutions as seen above as the arguments. It returns a function that receives the values for the substitutions. Upon passing the values for the inner function it executes the algorithm as mentioned in the doc to construct the final message. "The (n + 1)th argument corresponds to the substitution that takes place between the nth and (n + 1)th entries in the string array" function constructCustomMessage(staticWordsList, ...embeddedExpressionKeyList) { return (...valuesForEmbeddedExpressionList)=>{ let finalMessage = staticWordsList[0]; embeddedExpressionKeyList.forEach(function(expressionKey, index) { let expressionValue = valuesForEmbeddedExpressionList[index]; let nextStaticWord = staticWordsList[index+1]; if(expressionValue===null || expressionValue === undefined || expressionValue === ""){ // Replace the underscore '_' present at the beginning of string with empty value. nextStaticWord = nextStaticWord.replace(/^_/, ''); } finalMessage += expressionValue + nextStaticWord; }); // Replace the underscore '_' present at the end of string with empty value. finalMessage = finalMessage.replace(/_$/,''); return finalMessage ; }; } */ /* Sample Invocation Format var username; var tag; var handlerFunctiontoFormMessage = constructCustomMessage`<b>${username} says</b>: "${tag}"`; var outputString = handlerFunctiontoFormMessage('Mani Venkat', '& is a fun tag'); console.log(outputString); */