Home > Mobile >  Running a set of functions imported from a module in typescript
Running a set of functions imported from a module in typescript

Time:09-22

I am writing a program which needs to be able to import a bunch of functions from a separate file, and run them all (they each should return a value) in order to add that value to an expected output or transformation of the data.

I am working in a larger project, which is why I want the functions which get each value to be able to slot in without needing to change the source code of the library itself. In example: File 1

export function func1() : any {
    return {test1: "test1"}
}

export function func2() : any {
    return {test2: "test2"}
}

export function func3() : any {
    return {test3: "test3"}
}

File 2

import * as val_funcs from "path/to/val_func/file"

function get_val_list() : any {
// want to run every function in val_funcs
// like a loop, which runs each function, gets the value, and then returns the 
}

I am unsure how to accomplish this, or what the terms are I should google if I wanted to find an answer. I tried a couple variations on "how to run every function in a list in typescript", but did not find an answer that helped me.

CodePudding user response:

You can use an approach like this :


Object.values(val_funcs).forEach(fn=> fn());

Object.values will enumerate the values of the object. So the. If your file exports non-function things you can check its type like this:

.forEach(fn => if(typeof fn === "function") fn())

If you want to have the values returned from the function you can use Array.map instead of forEach :


const values = Object.values(val_funcs)
                    .filter(fn=> typeof fn === "function")
                    .map(fn=> fn());
  • Related