Unary Function Chainer

Unary Function Chainer
0.0 0

#1

Hi all,

I try to do code challenges on codewars at least once a day. Todays challenge topic was “Unary Function Chainer,” which I was able to solve (with the help of google), but I have a question regarding the solution.

The challenge can be found here.

My solution was:

function f1(x){ return x*2 }
function f2(x){ return x+2 }
function f3(x){ return Math.pow(x,2) }

function chained(functions) {
  return function inner (a) { //is a return here necessary to call function (a)?
    for (var b=0; b<functions.length; b++){
      a=functions[b](a);
        }
        return a
      }
      
    }
chained(f1,f2,f3)(4) //yields 4

I just want to make sure that I understand how this function chain works and was hoping you could help check my thought process.

Is it necessary to return my function inner (a) because that is the only way to call my function?

For instance, this didn’t work:

   function chained(functions) {
      function inner (a) { //is a return here necessary to call function (a)?
        for (var b=0; b<functions.length; b++){
          a=functions[b](a);
            }
            return a
          }
      return inner();

#2

In the second example, you’re invoking inner and returning its result. In the first example, you’re returning the inner function itself.

In the second example, if you just change inner() to inner, it would work.


#3

Thanks for the response. Would you mind explaining the difference between returning the function itself and returning the function’s result?

Does returning the function allow the second argument, in this case (4), to be passed as parameter a for inner. Whereas if I tried to invoke inner and return it’s result, it would still be looking at the (f1,f2,f3) argument?


#4

To explain the general concept, here’s a couple of examples.

function foo() {
	function bar() {
		return 'baz'
	}
	return bar;
}

var f = foo(); // returns the bar function itself.
f(); // this would call that function, returning 'baz'

function foo2() {
	function bar() {
		return 'baz'
	}
	return bar();
}

var f2 = foo2(); // this returns the bar function already invoked
f2 === 'baz'; // true

You have the right idea. Returning a function means we can call that function later. In the case of your program, that allows the (4).

If you return the function already invoked, it’s like calling the function with undefined instead of waiting for a value like 4.


#5

Great, Thank you! It’s much clearer now :slight_smile: