0

I want to make a recursive function. Consider I have a function named setoptions and I need to set 2 options so what I will do is call my function twice like this.

setoptions ("ajax",true);
setoptions ("lamda",false);

So to avoid it I should be able to write a function in a way that I can define multiple options like

setoptions({
    "lamda": false,
    "ajax": true
});

This is same as jquery`s attr function. like

$("#ff").attr("href","#");
$("#ff").attr("data-type","blue");
// can be used as 
$("#ff").attr({
    "data-type": "blue",
    "href": "#"
});

Kindly do not provide workarounds as I need to understand such recursion for learning.

Basic setOption function:

  var setOption =  function (val1, val2) {
    $.someplugin(val1, val);
  };
1
  • 1
    I'm not sure this should be called recusion... Commented Apr 11, 2014 at 9:56

3 Answers 3

1

Try this:

function setOption(){
  if(arguments.length==2)
    window.arguments[0] = arguments[1];
   else {
     for(var key in arguments[0]){
       setOption(key,arguments[0][key];
     }
   }
 }

Edit: I used window object, because I dunno where your values have to be set. So you might have to modify the if body statement in your code.

Edit2: As only this is can be called a recursion for me, this would be my approach. If you want to call a plugin, then I'd design that plugin to act recursively.

*EDIT 3 * Yeah I think something like this. Do note that it is still not recursive.console.log() line should not repeat.

 var setOption = function () {
     if (arguments.length == 2) {
         console.log(arguments[0], arguments[1]);
     } else if (jQuery.isPlainObject(arguments[0])) {
         for (var key in arguments[0]) {
             console.log(key, arguments[0][key]);
         }

     }
 }
 //USAGE:
 setOption({
     "href": "#",
     "data": "123",
 });

 setOption("cell", true);

}

Sign up to request clarification or add additional context in comments.

Comments

0

Try with:

var setOption =  function (data) {
  for (var key in data) {
    $.someplugin(key, data[key]);
  }
};

1 Comment

This wont take care of data on format like setOption("key","value");
0

This is I came up with. Let me know if there is a better approach. This is now true recursive.

var setOption = function () {
     if (jQuery.isPlainObject(arguments[0])) {
         for (var key in arguments[0]) {
             setOption(key, arguments[0][key]);
         }
     } else if (arguments.length == 2) {
         console.log(arguments[0], arguments[1]);
     }
}

//USAGE:
setOption({
  "href": "#",
  "data": "123",
});

setOption("cell", true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.