if(opt==='cat'){
return 'cat';
} else if(opt==='dog'){
return 'dog';
}
to
function name(opt) {
var opt = {
cat : 'cat',
dog : 'dog'
return opt || < something like this but can't remember
the return statement>
}
}
I am not able to find this pattern what to return pls rectify/ complete this pattern.
Your example is a bit too trivial to know what you're asking. The naive answer is
function name(opt) {
return opt;
}
Are you looking for the ternary operator?
function name(opt) {
return (opt === 'cat')
? 'cat'
: (opt === 'dog')
? 'dog'
: undefined;
}
Or something like a string enum?
const Animals = {
cat: 'cat',
dog: 'dog'
};
Animals.cat; // 'cat'
Animals.dog; // 'dog'
Or a real functional programming concept like a curried function? (This is not the best example though)
function name(opt) {
return opt || (arg) => name(arg);
}
name('cat') // 'cat'
name()('dog') // 'dog'
Let's assume that you would NOT return the same value you are passing... check this one out.
function name(opt) { return { 'cat' : 'Tom', 'dog' : 'Spike' }[opt]; }Cute trick, no? Even returns undefined on no match -- Though in practice making the object a global or scope restricted BEFORE the function would be more efficient the more times you call name().
Creating it as a property of the object is cute:
function name(opt) { // sadly we can't "this" here, lifting is good, it's not THAT good return name.names[opt]; } name.names = { 'cat' : 'Tom', 'dog' : 'Spike' };But at that point you might as well just:
var names = { 'cat' : 'Tom', 'dog' : 'Spike' };and just do names['cat'] instead of getting 'functions for nothing' involved by doing name('cat'). That's the problem with overdoing the 'functional pattern' nonsense, you often end up making more code than you need and introducing unnecessary overhead.