Building a spreadsheet - Step 59

Step 59

Your addCharacters(char1) is also returning a function, which returns another function. You need to make another function call to access that innermost function reference for the .map() callback. JavaScript allows you to immediately invoke returned functions:

Example Code

myFunc(1)("hi");

Immediately invoke the function returned from your addCharacters(char1) call, and pass char2 as the argument.

My Code

const addCharacters = character1 => character2 => num => charRange(character1, character2).map(elemValue(num));
  const rangeExpanded = x.replace(rangeRegex, (match, char1, num1, char2, num2) => rangeFromString(num1, num2).map(addCharacters(char1))(charRange(char2)));

To make it clear what I added in this step, it’s the bit at the very end: (charRange(char2))
Don’t know what I’m doing wrong. The instructions are poor.

Your addCharacters(char1) is also returning a function, which returns another function

I’m not so sure what these functions are. Are they charRange and elemValue?

access that innermost function

I’m guessing that’d be elemValue. But I tried that in the code, too and it didn’t work. I’m guessing I’m getting syntax wrong, but the example given doesn’t help much.
Thanks for your help!

charRange is a different function. addCharacters also returns a function, so it is that one.

It says to pass char2 as the argument. You need to chain the function call to the first function call inside map().

The example tells you how to do it:

myFunc(1)(“hi”);

We’re used to seeing functions being called like this:

myFunc()

To pass the argument to the innermost function its:

myFunc()();

1 Like
function add(num1) {
  return function (num2) {
    return num1 + num2;
  };
}
// capture the inner return function
const addTwoTo = add(2);
addTwoTo(40);
// 42

// invoke the inner return function immediately
add(5)(5);
// 10
2 Likes

I got it, thanks guys. But @lasjorg, I’m confused about how your code in the section “capture the inner return function” works.

Because addTwoTo is a variable, not a function, right? So how does “addTwoTo(40)” do anything? And why would it equate the number in the brackets (in our case 40) as being num2?

Your example under “invoke the inner treturn function immediately” makes sense to me.

add returns a function, so addTwoTo is that function. You can store functions inside variables and pass them around as values.

That is also how function expression works. You store the function definition inside a variable.

const fn = (args) => console.log(args)
fn("Log me")

If you log out addTwoTo you can see it is the inner function.

function add(num1) {
  return function (num2) {
    return num1 + num2;
  };
}

const addTwoTo = add(2);

console.log(addTwoTo);

Ć’ (num2) {
  return num1 + num2;
}
1 Like

I understand now. Thanks, my friend!