Skip to content
Advertisement

How can you calculate number of functions in a module when exporting/importing a custom module

Taking an instance of exporting these two functions in JS

module.js

const add = (a,b) => {
    return a+b;
};

const sub = (a,b) => {
    return a-b;
};

module.exports = {add, sub};

new.js

const {add, sub} = require('./module');

console.log(add(5,4));
console.log(sub(5,4));

Help, if I was to count how many functions am I importing on new.js file.

Advertisement

Answer

It would be interesting to know what you are trying to achieve as it is somewhat unusual, but it should be somewhat easy to get what you are after.

You can for example import everything from './module' as an object and then count the keys or similar in the imported object to get number of functions.

So for example:

const importedFunctions = require('./module');

console.log(Object.keys(importedFunctions).length)

Edit: I saw your reply in the comments. To extend it a bit further to call all imported functions with some values you could do something like this:

Object.values(importedFunctions).forEach((fn) => fn(5, 4))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement