Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass optional parameters to require()

so, I have this problem - and when I have a problem with JavaScript or node inevitably it is my coding that is the problem ;)

So at the risk of ridicule, this is the problem:

I have a module that has an optional parameter for config

Using the standard pattern, this is what I have:

module.exports = function(opts){
    return {
        // module instance
    };
}

and in the calling code there is this

var foo = require('bar')({option: value})

if there are no options to pass, the code looks like this

var foo = require('bar')({})

which kinda looks ugly

so, I wanted to do this

var foo = require('bar')

which doesn't work, as the exports is a function call

so, to the meat of the issue

a) is there any way of achieving this lofty goal ? b) is there a better pattern of passing parameters to a module ?

many thanks - and I hope that once the laughter has passed you will be able to send some help my way :)

like image 741
jmls Avatar asked Apr 30 '15 18:04

jmls


People also ask

How do you pass an optional parameter to a function?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.

How do you pass optional parameters in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

How do I set optional parameters?

Using Optional Attribute Here for the [Optional] attribute is used to specify the optional parameter. Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception.

Can we pass optional parameters in Java?

Introduction to optional parameters in Java Unlike some languages such as Kotlin and Python, Java doesn't provide built-in support for optional parameter values. Callers of a method must supply all of the variables defined in the method declaration.


1 Answers

Instead of removing the function call completely, you could make the options argument options to remove the need for an empty object:

module.exports = function(opts) {
    opts = opts || {};
    return {
        // module instance
    };
}

It doesn't completely remove the need for () but is better than ({}).

like image 142
trumank Avatar answered Nov 15 '22 00:11

trumank