1

I am trying to create something like this as below

export function f1(param1: string, param2: string) {
    console.log('Hello', param1, param2);
}

export function f2(param3: string) {
    console.log('world', param3);
}

interface Metadata {
    functionName: string;
    functionParams: any;
}

const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', {functionName: 'f1', functionParams: {param1: 'any', param2:'any1'}}],
    ['action2', {functionName: 'f2', functionParams: {param3: 'any2'}}]
])

So basically I want to call f1 or f2 function after reading it through a testMap. The idea is to store all action and their mappings against a function and execute actions in one go instead of creating multiple if and else statements.

Can somebody help I can achieve this ?

1
  • 2
    is there any reason you are passing function name instead of actual function in the map? e.g. ['action1', {functionName: f1, functionParams: ['any','any1']}]? Commented Feb 10, 2022 at 23:46

1 Answer 1

1

You can't reference and call a function by passing its name as a string (without doing some eval black magic that I cannot in good conscience recommend). Instead, you should pass the function itself:

export function f1(param1: string, param2: string) { }

export function f2(param3: string) { }

// Change your interface to accept a function instead of a string:
interface Metadata {
    invoke: (...args: any[]) => any;
    functionParams: any[];
}

// Pass f1 or f2 (the function references) instead of 'f1' or 'f2':
const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', { invoke: f1, functionParams: ['any', 'any1'] }],
    ['action2', { invoke: f2, functionParams: ['any2'] }]
])

Playground example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.