www.webdeveloper.com
Results 1 to 3 of 3

Thread: Function Callback re-factored

  1. #1
    Join Date
    Apr 2011
    Location
    Berlin, Germany
    Posts
    8

    Function Callback re-factored

    Please help. 1st function works but 2nd which is a re-factor of the 1st does not work? Thanks.

    //////// 1. WORKS
    function addOne(a) { return a + 1; }

    function multiplyByTwo(a, b, c, callback) {
    var i, myArr = [];
    //console.log(arguments)

    for (i = 0; i < 3; i++) {
    //console.log(callback(arguments[i] * 2 ))
    myArr[i] = callback(arguments[i] * 2);
    };
    return myArr;
    }
    console.log(multiplyByTwo(1, 2, 3, addOne))

    /////// 2. Does Not WORK
    function multiplyByTwo(a, b, c) {
    var i, myArr = [];
    //console.log(arguments)

    for (i = 0; i < 3; i++) {
    //console.log(arguments[i] * 2 )
    myArr[i] = arguments[i] * 2;
    };
    return myArr;
    }
    console.log(multiplyByTwo(1, 2, 3, function (x) {
    return x + 1;
    }));

  2. #2
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by ab2qik View Post

    /////// 2. Does Not WORK
    function multiplyByTwo(a, b, c) {
    var i, myArr = [];
    //console.log(arguments)

    for (i = 0; i < 3; i++) {
    //console.log(arguments[i] * 2 )
    myArr[i] = arguments[i] * 2;
    };
    return myArr;
    }
    console.log(multiplyByTwo(1, 2, 3, function (x) {
    return x + 1;
    }));
    It outputs [2, 4, 6], which is what I would expect.
    What were you expecting and why are you passing it a callback that it's not coded to handle?

  3. #3
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    Are you trying to create an overloaded function in Javascript? If so then it's not going to work :P

    But you could get the "multiplyByTwo" function to support callbacks or not:

    Code:
    function addOne(a)
    {
    	return a + 1;
    }
    
    function multiplyByTwo(a, b, c, callback)
    {
    	var i, myArr = [];
    	//console.log(arguments)
    
    	for (i = 0; i < 3; i++) {
    		//console.log(callback(arguments[i] * 2 ))
    		myArr[i] = callback ? callback(arguments[i] * 2) : arguments[i] * 2;
    	}
    	return myArr;
    }
    
    console.log(multiplyByTwo(1, 2, 3))
    console.log(multiplyByTwo(1, 2, 3, addOne))
    console.log(multiplyByTwo(1, 2, 3, function (x)
    {
    	return x + 2;
    }));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles