Created
May 3, 2016 14:26
-
-
Save Lcfvs/56184afb8dbe1fdd4f6dcb4fe1b653b1 to your computer and use it in GitHub Desktop.
Simple & controlled template string emulation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @module: string-inject | |
| * @version: 1.0.0 | |
| * @author: Lcf.vs | |
| * @copyright: © 2015 | |
| * @license: MIT | |
| * @exports: {function} inject(name, str, data) | |
| * @description: Injects some map-based data into a string | |
| * @param: {string} name | |
| * @description: The map name | |
| * @param: {string} str | |
| * @description: The string which needs to be rewritten | |
| * @param: {object} map | |
| * @description: The data to inject | |
| * @return: {string} | |
| * @description: The rewritten string | |
| */ | |
| 'use strict'; | |
| const ADD_SLASH_PATTERN = /\\/g; | |
| const MAP_PATTERN = /(\$\{)(\w+)/g; | |
| var inject; | |
| inject = function({ | |
| name: name, | |
| map: map, | |
| str: str, | |
| global: global, | |
| require: require, | |
| module: module, | |
| exports: exports, | |
| __dirname: __dirname, | |
| __filename: __filename, | |
| define: define | |
| }) { | |
| var sanitized; | |
| sanitized = str | |
| .replace(ADD_SLASH_PATTERN, '\\\\') | |
| .replace(MAP_PATTERN, function(match, prefix, suffix) { | |
| if (suffix === name) { | |
| return prefix + suffix; | |
| } | |
| return '\\' + prefix + suffix; | |
| }); | |
| sanitized = 'return function() {return ' + sanitized + ';}();'; | |
| return Function( | |
| name, | |
| 'ADD_SLASH_PATTERN', | |
| 'MAP_PATTERN', | |
| 'inject', | |
| 'sanitized', | |
| 'name', | |
| 'str', | |
| `return \`${sanitized}\`;` | |
| ).call(null, map); | |
| }; | |
| module.exports = inject; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage :