1

Hi I'm trying to run the following function:

 function add (a, b) {
 return a + b;
 }
 var make_lazy = function (add, a, b) {
 return function () {
 add(a,b);
 }
 }

Basically what I'm trying to do is to pass another function as an argument and its parameters to the make_lazy function - and then run the function that was passed in as the argument along with the other two parameters. I get undefined is not function as an error when I try to run the code.

asked Mar 7, 2015 at 11:50

4 Answers 4

2

You forgot the return statement in the anonymous function that you're returning from make_lazy:

var make_lazy = function (add, a, b) {
 return function () {
 return add(a,b) // <----- here
 }
}
answered Mar 7, 2015 at 11:57
Sign up to request clarification or add additional context in comments.

Comments

1

I think you are trying for something like this.

function add (a, b) {
 return a + b;
}
 var make_lazy = function (a, b) {
 return function () {
 return add(a,b);
 }
}

Then you can call var lazy = make_lazy(3,5); and later call lazy() to get 8

answered Mar 7, 2015 at 11:56

2 Comments

I think you missed the main issue (see my answer). But it would indeed be silly to pass add if it's the only function you're ever going to pass.
I dont understand. Dont you see return keyword in question's make_lazy function?
0

Wrap you lazy function body inside a self calling function and return.

function add (a, b) {
 return a + b;
 }
 var make_lazy = function (add, a, b) {
 return (function () {
 add(a,b);
 })();
 }
answered Mar 7, 2015 at 12:02

1 Comment

You're missing the point of making a lazy function. That means he wants to run it only if he has to. Presumably the "add" function is an example and in his real code it's much more expensive.
-1

Here's my point of view.

When you assign a function to make_lazy variable, after that you should make an invocation make_lazy() with the same params as they were in the definition of that function:

make_lazy(function expression, a, b);

This portion:

function (add, a, b)

just makes add a local variable, this is not the same as add(a,b) which is defined above.

To make the code work, try to invoke make_lazy as

make_lazy(add, 3, 4)
answered Mar 7, 2015 at 12:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.