typed-string-interpolation
Version:
String interpolation with correct return type based on passed variable substitutions
2 lines (1 loc) • 553 B
JavaScript
function c(e,p,{pattern:b=/\{{([^{]+)}}/g,sanity:a=!0,raw:d=!1}={}){if(!e&&a)throw new Error("Empty string");let V=a?Object.keys(p):void 0,n=[],t=0,i=0,l=!0,r;for(;r=b.exec(e);){let u=r.index,w=r[0],o=r[1];if(u>t&&n.push(e.slice(t,u)),a&&o&&!V.includes(o))throw new Error(`Variable '${o}' not found`);let s=p[o];l=l&&(typeof s=="string"||typeof s=="number"),n.push(s),t=u+w.length,i++}if(!i)return e;if(t<e.length&&n.push(e.slice(t)),a&&i!==V.length)throw new Error("Variable count mismatch");return l&&!d?n.join(""):n}export{c as stringInterpolation};