Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running a set of functions imported from a module in typescript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading