/**
 * @since Last modified: 2024/05/17 01:19:34
 * @function renderTpl
 * @description Get template string through parameters.Cut the template strings into fragments through labels, and put into the array through the PUSH method, and finally merge into a new string.
 * @param {string} html - Text string with variables, for example: html=`I like {{this.name}}, she is {{this.age}} years old`.
 * @param {object|array} data - Variable key-value pairs, for example: data={name:'Lily',age:20}.
 * @returns {string}  - Get the string after the variable.
 * @see {@link https://codepen.io/axui/pen/oNmWrjp|demo @ codepen}
 * @example
 * ax.renderTpl(`My name is {{ this.name }}`,{name:'axui'})
 * <!--return 'My name is axui'-->
 */
'use strict';
import requireTypes from "./requireTypes";
const renderTpl = (html, data) => {
    requireTypes(html, 'string');
    requireTypes(data, ['array', 'object']);
    if (!html || Object.keys(data).length === 0) {
        return '';
    }
    let regStart = '\\{\\{', regEnd = '\\}\\}', exeEnd = '/', tplReg = new RegExp(`${regStart}([\\s\\S]+?)?${regEnd}`, 'g'), code = 'let str=[];\n', cursor = 0, match, result = '', add = (fragment, isJs) => {
        isJs ? (code += (fragment.endsWith(exeEnd) ? fragment.replace('=&gt;', '=>').slice(0, -1) + '\n' : 'str.push(' + fragment + ');\n'))
            : (code += (fragment !== '' ? 'str.push("' + fragment.replace(/"/g, '\\"') + '");\n' : ''));
        return add;
    };
    while (match = tplReg.exec(html)) {
        add(html.slice(cursor, match.index))(match[1], true);
        cursor = match.index + match[0].length;
    }
    add(html.slice(cursor));
    code += `return str.join('');`;
    try {
        result = new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
    }
    catch (err) {
        console.error(`'${err.message}'`, ' in \n', code, '\n');
    }
    return result;
};
export default renderTpl;
