newbie programmer
newbie programmer

Reputation: 97

How can I run all functions with their corresponding arguments at once by a single `run()`?

If I have two files,

File 1

exports.run = () => {
    console.log(test.property, test2.property, etc.property)
};
exports.info = {
    name : "test"
}

File 2

const fs = require('fs');
let test;
let test2;
let etc;
test.property = "test";
test2.property = "test2";
etc.property = "etc";
let functions = new Map();
fs.readdir('./', (err, files) => {
    if (err) console.error(err);
    files.forEach(f => {
        let props = require(`./${f}`);
        functions.set(props.info.name, props);
    });
});
functions.get("test").run()

As I have it right now, I need to manually add each variable as a parameter in file 1 and in file 2 I need to manually pass each through the .run(). This is tedious and annoying so is there anyway that I can just scope the .run() so that it uses all of the current variables?

Upvotes: 0

Views: 93

Answers (1)

tigercosmos
tigercosmos

Reputation: 345

I'm not sure whether it's your wanted code


const args = {
    foo: ["a", "b"],
    bar: ["c", "d", "e"]
}

const map = new Map();


function Foo(first, second) {
    console.log(first, second)
}

function Bar(first, second, third) {
    console.log(first, second, third)
}

map.set("foo", Foo);
map.set("bar", Bar);

function run() {
    for(const key of map.keys()) {
        const func = map.get(key);
        func.apply(undefined, args[key])
    }
}

run();

// output
// a b
// c d e

the key point is apply function, which can call a function reference with its arguments as apply's arguments. You can check out more on MDN of apply.

Upvotes: 1

Related Questions