实现思路
- 模板标签函数接收两个参数:字符串字面量数组和参数数组。
- 利用闭包,将接收到的参数存储起来。
- 每次调用返回一个新函数,这个新函数继续接收参数并存储,直到满足条件返回最终结果。
代码示例
function curryWithTemplateTag(template, ...args) {
return function innerCurry(...innerArgs) {
const allArgs = [...args, ...innerArgs];
if (allArgs.length >= template.length - 1) {
let result = '';
for (let i = 0; i < template.length - 1; i++) {
result += template[i] + allArgs[i];
}
result += template[template.length - 1];
return result;
} else {
return innerCurry;
}
};
}
// 使用示例
const curriedFunction = curryWithTemplateTag`Hello, ${}, you are {} years old.`;
console.log(curriedFunction('John')(25));