0

A friend asked me to design a function that does the following : f1()()()()(0) should give the output as 4. f1()(0) should give output as 1. It is the number of preceding parentheses before 0 is passed. I searched thoroughly on how it should be done. Got some concepts to string together: like IIFE, Anonymous Functions and Lexical Scope. Does this use a more advanced javascript concept function that should be known? Here is the image of what needs to be done

1 Answers1

0

No advanced concepts. You only need to know how to return a function from another function.


I would prefer to call the function f0 because f0(0) obviously should return 0. Then we can imagine all such kinds of functions that return their level of parenthetication—for example, f42(0) returns 42.

When called without a parameter, f0() should return f1, so that f0()(0) is 1, and so on. That is an easy thing to do:

function f0(x) {
  return (x === 0) ? 0 : f1(x);
}

Obviously, we do not want to write down an infinity of functions like this. Let's make a function factory that will build them automatically as needed:

function factory(level) {
  function f_level(x) {
    return (x === 0) ? level : factory(level + 1);
  }
  return f_level;
}

The factory always returns a function, and factory(0) is exactly the function f0 you wanted.

emu
  • 1,597
  • 16
  • 20