mcgrailm
mcgrailm

Reputation: 17640

Is it possible to merge these two functions

I have a bunch of functions that look like this

'tea' : function (caller) {
    this.speak(this.randomOption('tea_msg'));

},

'chill' : function (caller) {
    this.speak(this.randomOption('chill_msg'));

},

and what i want is to merge them to something like this

'tea' ,'chill': function (caller) {
     // get which function name was called in var lets call it fun
    this.speak(this.randomOption(fun +'_msg'));
}

Is this possible or am I going about this the wrong way?

Upvotes: 1

Views: 115

Answers (3)

hugomg
hugomg

Reputation: 69934

You can make a function-maker-function that would get pretty close

function speaker(message){ return function(caller){
    this.speak(this.randomOption(message + '_msg');
};}

{
    'tea': speaker('tea'),
    'chill': speaker('chill')
}

And if you want to avoid retyping the 'tea' and 'chill' you can use the [] object-subscripting syntax together with some sort of loop:

var funs = {};
var msgs = ['tea', 'chill'];
for(var i=0; i<msgs.length; i++){
    var msg = msgs[i];
    funs[msg] = speaker(msg);
}

Just be careful about the closures-inside-for-loops if you want to write the speaker function inline instead.

Upvotes: 4

Zirak
Zirak

Reputation: 39808

[ 'tea', 'chill', 'elephant', 'moose' ].forEach(function (val) {

    //creating a closure so `val` is saved
    (function (val) {
        obj[ val ] = function ( caller ) {
            this.speak( this.randomOption(val + '_msg') );
        };
    }(val));

});

You can also write a generic say function:

say : function ( caller, type ) {
    this.speak( this.randomOption(type + '_msg') );
}

Upvotes: 1

Helen
Helen

Reputation: 811

You could pass the function name as a variable?

'text': function (caller, functionName) {
     // get which function name was called in var lets call it fun
    this.speak(this.randomOption(functionName +'_msg'));
}

Upvotes: 1

Related Questions