UNPKG

hydrate-text

Version:

A small, dependency-free and strongly typed template engine.

71 lines (68 loc) 2.13 kB
/* === Constants === */ const DEFAULT_INTERPOLATION_OPTIONS = { prefix: "{", suffix: "}", }; /* === Utility functions === */ /* Used to match `RegExp`. Syntax characters: http://ecma-international.org/ecma-262/7.0/#sec-patterns. */ const reRegExpChar = /[\\^$.*+?()[\]{}|]/g; const reHasRegExpChar = RegExp(reRegExpChar.source); /* Source: https://github.com/lodash/lodash/blob/master/escapeRegExp.js Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in `value`. */ const escapeRegExp = (value) => { if (!value || !reHasRegExpChar.test(value)) { return value; } return value.replace(reRegExpChar, "\\$&"); }; /* Source: https://github.com/lodash/lodash/blob/master/isUndefined.js Checks if `value` is `undefined`. */ const isUndefined = (value) => { return value === undefined; }; /* === Main functions === */ const hydrateText = (text, variables, interpolationOptions) => { if (isUndefined(variables)) { return text; } const { prefix, suffix } = isUndefined(interpolationOptions) ? DEFAULT_INTERPOLATION_OPTIONS : interpolationOptions; const resultText = Object.entries(variables).reduce( (resultText, [name, value]) => { const regExpSource = escapeRegExp(`${prefix}${name}${suffix}`); const regExp = new RegExp(regExpSource, "g"); return resultText.replace(regExp, String(value)); }, text, ); return resultText; }; const configureHydrateText = (interpolationOptionsFromConfigurer) => (text, variables, interpolationOptionsFromInnerFunction) => { const interpolationOptions = isUndefined( interpolationOptionsFromInnerFunction, ) ? interpolationOptionsFromConfigurer : interpolationOptionsFromInnerFunction; return hydrateText( text, variables, /* `interpolationOptions` inherits `prefix` and `suffix` types from `interpolationOptionsFromConfigurer`, so it is not necessary to define the union. */ interpolationOptions, ); }; export { configureHydrateText, hydrateText };