JavaScript 中的动态函数映射

问题描述 投票:0回答:1

我正在用 JavaScript 实现动态函数映射机制。

这是我的代码:

class FunctionMapper {
    constructor() {
        this.functions = {};
    }

    register(name, func) {
        this.functions[name] = func;
    }

    invoke(name, ...args) {
        const func = this.functions[name];
        if (func) {
            return func(...args);
        } else {
            return null;
        }
    }

    listFunctions() {
        return Object.keys(this.functions);
    }
}

我的代码哪里缺少?

目标:目标是创建一个系统,允许以不同名称注册函数,然后使用注册的名称动态调用这些函数。

javascript algorithm data-structures dynamic-programming
1个回答
0
投票

解决方案:

如果未找到请求的函数,则调用方法会抛出错误,这可确保用户了解未注册的函数名称的任何问题。

class FunctionMapper {
    constructor() {
        this.functions = {};
    }

    register(name, func) {
        this.functions[name] = func;
    }

    invoke(name, ...args) {
        const func = this.functions[name];
        if (func) {
            return func(...args);
        } else {
            throw new Error(`Function '${name}' not found.`);
        }
    }

    listFunctions() {
        return Object.keys(this.functions);
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.