MST

星途 面试题库

面试题:JavaScript模板标签与函数柯里化结合应用

如何利用JavaScript模板标签实现函数柯里化?请详细说明实现思路,并编写代码示例,展示一个可以接受多个参数,通过模板标签逐步处理参数的柯里化函数。
41.1万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 模板标签函数接收两个参数:字符串字面量数组和参数数组。
  2. 利用闭包,将接收到的参数存储起来。
  3. 每次调用返回一个新函数,这个新函数继续接收参数并存储,直到满足条件返回最终结果。

代码示例

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));