loading...

Convert to 2 functions to one function

jmjjeena profile image J E E N A R J U N ・1 min read

Convert to 2 functions to one function

0

Following are 2 functions to get the options in the dropdown. I want to make it to one function rather than 2 different function. There are few options different based on fromtype/totype. But most like case A, I, W etc are common for both the functions. How to make…

Discussion

pic
Editor guide
Collapse
dinsmoredesign profile image
Derek D

You could do something like this for your first function, then just combine your options for the second function into the map/set, assuming those options aren't available as from options:


const getFromTypeOptionKey = (fromType, fromMetaType) => {

    const metaMap = new Map([
        [ 'W2', ['W'] ],
        [ 'A1', ['A'] ],
        [ 'I1', ['C'] ],
        [ 'L', ['C'] ],
        [ 'CH', ['C'] ],
        [ 'C1', ['C'] ],
        [ 'AT', ['C'] ]
    ]);

    if (fromType === 'E') { return metaMap.get(fromMetaType) || [ 'A', 'W', 'C', 'I', 'CK' ] };
    if (fromType === 'W1') { return ['W'] };

    const typeSet = new Set(['A', 'I', 'W', 'R']);

    return typeSet.has(fromType) ? [ fromType ] : [];

};

P.S. I hate switch statements, IMO this is a much easier to read solution if you understand Maps/Sets ;) It's also half the amount of code (less if you combine the options from the second function into it).

Collapse
jmjjeena profile image
J E E N A R J U N Author

Thanks Derek :) I will test it out and let you know how it goes.

Collapse
dinsmoredesign profile image
Derek D

Sure thing! My original idea was actually to just take any of your strings (assuming it's not an option that returns C or the large array from the default of E) and remove any index after 0 and return that inside an array, as something like W, W1 and W2 all map to the same value, but I don't know what the rest of your data looks like in order to do this.

P.S. Sorry you got downvoted on SO, people on there are so dumb :(