A long list of javascript options; looking for an alternative

I am writing a javascript function that has a rather long list of parameters:

FormatGrid(ID, BackColor, SideColor, HiddenColor, SmallTextClass....) 

This works well, but when calling this function, every time you call this function, you need to remember each parameter and the order in which they enter, because the function takes a total of 9 parameters (and I can add 2 more).

I am wondering if there is an elegant solution there.

Thanks for your suggestions.

+4
source share
5 answers

you can just pass the object

 FormatGrid(myObject){ //your code } 

If your myObject looks like {ID: '1', BackColor: 'red', SideColor: 'red', HiddenColor: 'black', SmallTextClass: 'true'...}

+5
source

In general, I like the following format

 function foo(requiredVar1,requiredVar2,..,options) { //here is where options is merged with default params var defaultOptions = {}; options = Object.extend(defaultOptions,(options || {})); } 

where options is the map {option1:value1, ...}

+1
source

Pass the object to your function as a parameter:

 function FormatGrid(objectParameter) { // ... } FormatGrid({ key1: "val1", key2: "val2", ... }); 
0
source

In addition, you can combine the specified function parameters with these by default:

 function mergeWithDefaults (params, defaults={}) { var toRet = {}; for (atr in defaults) toRet[atr] = defaults[atr]; for (atr in params) toRet[atr] = params[atr]; return toRet; } 

Then you can use this function for the default parameters in your function:

 FormatGrid (params) { params = mergeWithDefaults (params, { 'backColor': '0xfff' }); // Body of your function using the params variable which has been defaulted. } 

If you call FormatGrid with parameters containing backColor, it will be used, otherwise it will be set by default by default (here "0xfff").

Hope this helps :) Pierre.

0
source

An alternative to using the options / params object is to create new versions of the function that already have some values. This is useful when you need to call the same function multiple times without changing the value of many arguments.

 // bad name; a good name would say something about // the purpose of the new function function makeShorterFormatGrid(ID, BackColor, SideColor) { return function(HiddenColor, SmallTextClass) { FormatGrid(ID, BackColor, SideColor, HiddenColor, SmallTextClass); } } var ShortFormatGrid = makeShorterFormatGrid("myId", "#ffffff", "#000000"); // the first three arguments are already filled in ShortFormatGrid("#c0c0c0", "className"); ShortFormatGrid("#cccccc", "otherClassName"); 
0
source

Source: https://habr.com/ru/post/1345457/


All Articles