Trouble understanding a basic concept in Javascript Higher Order Functions - javascript

I am having a little bit of trouble understanding Higher Order Functions in javascript.
Can someone explain to me the difference of what's going on in these two situations?
Scenario 1:
// A function that takes in a number (x) and adds one to it.
function doMath(x){
return function (x){
return x + 1;
}
}
var didMath = doMath(5);
console.log(didMath()); // returns error
var didMath = doMath();
console.log(didMath(5)); // returns 6
var didMath = doMath(100);
console.log(didMath(5)); // still returns 6
Scenario 2:
function doMath2(x,callback){
return callback(x);
}
function add(x){
return x + 1;
}
console.log(doMath2(5,add)); // returns 6, works perfectly fine
I was under the impression that closures have access to parameters from their containing functions. Why is it that in Scenario 1, the "x" param in doMath is not accessible by the contained function?

what is happening here is you are never storing the value of x, you always return a new function, see this example it should work as you expect and maybe helps you to undersant
function doMath(x){
var y = x;
return function(y){
return y + 1;
}
}

In scenario 1
The first one outputs an error because the returned function expects an argument and you don't give one. If you remove the argument it works:
// A function that takes in a number (x) and adds one to it.
function doMath(x){
return function (){ // <--- here
return x + 1;
}
}
var didMath = doMath(5);
console.log(didMath());
In your two other examples you do give an argument and that is the one taken into account. Not the value that you give as parameter to doMath()

Related

Creating an Arithmetic Task Runner

I have been tasked to create an Arithmetic Task Runner as part of my assignment.
Up until today I've never used NodeJS or even the terminal to execute a script.
I have been working on this for the past 5 hours and still no luck. I have avoided coming here and asking as I'd like to figure it out for myself, however, I have succumbed to desperately needing help.
This is the code I have so far:
class ArithmeticTaskRunner {
static set taskCount(counter) {
throw new('This is a readOnly accessor, the value is ${value}');
}
add(y) {
this.y = y || 0
console.log(y)
}
minus(x) {
this.x = Math.abs(this.y) * -1;
console.log(this.x);
};
multiply(z) {
this.z = z * this.x;
console.log(this.z)
}
execute(startValue) {
this.startValue = startValue + this.y
this.y = this.startValue
console.log(this.startValue)
this.startValue = this.minus
console.log(this.startValue)
this.startValue = this.multiply(this.startValue)
console.log(this.startValue)
}
}
tasks = [
function() { minus()},
function() { multiply(z)},
function() { add(x)},
function() { execute(x)}
]
This is nowhere near perfect, but it's 80%-90% near completion.
This is the task I have been given:
You should implement a class called ArithmeticTaskRunner with the following:
- An instance variable named tasks which is initialised to an empty array upon
creation.
- A method named addNegationTask which adds an anonymous function to the
tasks array. This anonymous function should take one argument, x, and return the
negation, -x.
- A method named addAdditionTask which takes a single argument y, and adds
an anonymous function to the tasks array. This anonymous function should take
one argument, x, and return the result x + y.
- A method named addMultiplicationTask which takes a single argument y,
and adds an anonymous function to the tasks array. This anonymous function
should take one argument, x, and return the result x * y.
- A read-only accessor named taskCount which returns the number of queued tasks.
- A method named execute, which takes a single argument named startValue.
If omitted, startValue defaults to zero. Starting at startValue, this method should iterate over the tasks array executing each function on the current value. It then returns the resulting number after all arithmetic operations have been executed.
I'd be grateful for any help I could get.
The issues I have are the following: The execute method (trying to make the startValue, after the addition, a negative), the multiplication method and the fact I cannot call the addition method twice without overriding the value. The examples of the program fully working have shown I should allow for a method to be called multiple times without overriding the previous value.
I know there's a rule where it's one question per issue, I concede that. But if anyone can help me out with any of the issues I will truly be grateful and I will compensate people for their efforts.
Thank you.
Edit - This is an example of both the expected inputs/outputs
> let taskRunner = new ArithmeticTaskRunner()
undefined
> taskRunner.addAdditionTask(2)
undefined
> taskRunner.addMultiplicationTask(4)
undefined
> taskRunner.addAdditionTask(10)
undefined
> taskRunner.execute(2)
26
> taskRunner.execute(-2)
10
I don't want to provide the whole answer because this is an assignment for you, but here's some code that might help you out. This starts with 5 then calls doubleIt and then calls addOne to arrive at 11.
It does this by creating an array of functions, each one performs a simple task and returns the result of its input modified in some way.
Then it creates a function called execute that uses Array.reduce to call the first function in the array with a given initial value, then repeatedly calls each function in the array on the result. Check the documentation for Array.reduce if you're confused about how it works.
doubleIt = x => x * 2;
addOne = x => x + 1;
tasks = [doubleIt, addOne];
execute = (initial) => tasks.reduce((x,fn) => fn(x), initial)
document.write(execute(5))
Hint #2
class ArithmeticTaskRunner {
constructor() {
this.tasks = [];
}
addAdditionTask(arg) {
this.tasks.push(x => x + arg);
}
addMultiplicationTask(arg) {
this.tasks.push(x => x * arg);
}
execute(startValue) {
return this.tasks.reduce((x, fn) => fn(x), startValue);
}
}
let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(2)
taskRunner.addMultiplicationTask(4)
taskRunner.addAdditionTask(10)
document.write(taskRunner.execute(2));
document.write(', ');
document.write(taskRunner.execute(-2));

Does it ever make sense to include a value in the first next call to generator iterator?

As the question states, does it ever make sense to pass a value to the first iterator.next() call or will it always be ignored? As an example:
function* foo(x) {
var y = 2 * (yield(x + 1));
var z = yield(y / 3);
return (x + y + z);
}
var it = foo(5);
// note: not sending anything into `next()` here
console.log(it.next()); // { value:6, done:false }
console.log(it.next(12)); // { value:8, done:false }
console.log(it.next(13)); // { value:42, done:true }
Notice there is not a value being passed to the first next(). However, in the article I'm trying to learn from, it goes on to say:
But if we did pass in a value to that first next(..) call, nothing bad would happen. It would just be a tossed-away value
Okay. That makes sense. But now I'm curious to know if there is a use case (or if it's even possible to utilize) where passing in a value has a benefit.
Article: https://davidwalsh.name/es6-generators
Will it always be ignored?
Yes.
Is a use case where passing in a value has a benefit?
When it simplifies the rest of your code. In your example, that could be using a loop instead of writing it out:
const it = foo(5);
for (let i=11; i<=13; i++)
console.log(it.next(i));
Now we're passing 11 into the first call to .next even if there's no use for the value anywhere.

What is being passed into this 'function(x)'?

I'm having a hard time grasping some finer details of javascript, I have this function function(x) it doesn't seem to be receiving any parameters. Maybe I'm not understanding the Math.sin part. I'm not sure. Any ideas on what is happening?
function makeDerivative( f, deltaX )
{
var deriv = function(x) // x isn't designated anywhere
{
return ( f(x + deltaX) - f(x) )/ deltaX;
}
return deriv;
}
var cos = makeDerivative( Math.sin, 0.000001);
// cos(0) ~> 1
// cos(pi/2) ~> 0
Update
I tried this instead and got NaN, then 15
function addthings(x, y)
{
var addition = function(m)
{
return( x + y + m);
}
return addition;
}
var add = addthings(5, 5);
alert(add());
alert(add(5));
To understand how that code works you have to read more about currying in functional javascript and functions closures.
The outer function returns the inner function, so everything you pass to
cos later theoretically is what you pass into the inner function. Imagine calling it like this:
console.log(makeDerivative( Math.sin, 0.000001)(0)); // 1
would output the same as if you're doing it as described
console.log(cos(0)) // 1
as cos is assigned reference to a function (the one that gets returned by makeDerivative).
The other answers touch on the issue, but I'm going to try to get to the core of it.
JavaScript variables are untyped, which means that they can dynamically change what kind of variable they are. On a simple level, this means that var a can be instantiated as an array, and then later assigned as a string on the fly.
But you can also store entire functions within those untyped variables. For example;
var test = 'hey'
console.log(test) //:: hey
test = function(input){ console.log('inner function: ' + input) }
console.log(test) //:: function(input){ console.log('inner function' + input) }
test() //:: inner function
test('with input') //:: inner function with input
Where //:: _____ represents the output to the console.
So the function you are using returns another dynamic function. You can then call that function in a normal fashion, inputting the value for x when you call it.
Well, you don't really call the function in the code you posted.
The makeDerivative gets reference to Math.sin function and inside it uses it to create reference to function which compute derivation of the passed function (see the f parameter).
In your example this reference is assigned to cos variable. If you called it with (0) argument, you would get 1 as return value and the argument (0) would be passed into that deriv function...

lexical scoping in javascript

I'm reading this book: http://eloquentjavascript.net/ which I think is brilliant.
However I'm having difficulty understanding the following function, where does the function add(number) get its argument from?
function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1)); // gives 9
I thought the answer would be 7 to this show(addTwo(1) + addFive(1));
In makeAddFunction(2), amount is 2, but what would number be? so number + 2...
NB: show function is pretty much echo in php.
makeAddFunction returns a new function. The new function takes a param, number, and adds it to whatever was originally given to makeAddFunction.
var addTwo = makeAddFunction(2);
// addTwo is now a function which you can call with a numeric argument ('number')
// anything you pass to it will have two added to it
var five = addTwo( 3 ); // add two to three (makes five)
See JAAulde's answer for what makeAddFunction's purpose is, which was really the main question, imo
The answer to your second question is, you generate two functions. They look like this (basically):
var addTwo = function add(number) {
return number + 2;
};
var addFive = function add(number) {
return number + 5;
};
It should be obvious why you get:
addTwo(1) + addFive(1)
(1 + 2) + (1 + 5) = 9 now.
What would number be? Number is an argument to the returned function. I think you're thinking about this too hard.
makeAddFunction(5) effectively returns a named reference to function(number) { return number + 5; }

Understanding Snippet of Javascript

My professor has given us the following snippet of Javascript which we are supposed to analyze:
function createMultiplyer(multiple) {
n = multiple;
return function(num) {
return num * n;
};
}
var fiveMultiplyer = createMultiplyer(15);
var x = fiveMultiplyer(10);
alert(x);
alert(fiveMultiplyer);
This piece of code outputs an alert containing the text "150" followed by another alert which reads function(num) { return num * n; }. However, I cannot seem to understand why that is the case.
Can someone help me trace through the code and explain what is happening?
1 Let's consider line
var fiveMultiplyer = createMultiplyer(15);
After it, fiveMultiplyer variable will have return value of createMultiplyer function (that's how functions work). And that return value is
function(num) {
return num * n;
};
So, the code is similar to this (about n later)
var fiveMultiplyer = function(num) {
return num * n;
};
2 The next line is
var x = fiveMultiplyer(10);
Here we just invoke the function above. It also uses variable n: that variable is set in createMultiplyer function: n = multiple;. Thus, in our case n is 15 and fiveMultiplyer(10) is equivalent to 10 * 15.
That's all. Hope it helps.
edit
I'll also note that n is a global variable the way it's declared. So, you can access it from anywhere in the code.
var fiveMultiplyer = createMultiplyer(15); // Create a function that multiplies with 15
This function is locally known as fiveMultiplier
var x = fiveMultiplyer(10); // Invoke the multiply-by-15 with argument 10
The result is locally known as x
alert(x); // 150
alert(fiveMultiplyer); // The definition of multiply-by-15 as
// it is returned from createMultiplyer
function createMultiplyer(multiple) { // Returns a new function which
// multiplies with "multiple"
[var] n = multiple; // Note: "var" should have been used to keep "n"
// in scope (within "createMultiplyer").
return function(num) { // Return definition of multiplier function
return num * n; // "num" = arg. when invoked, "n" = multiplier at
// define time (when "createMultiplyer" was called)
};
}
The best way to think of it is as a class or object. var fiveMultiplyer is creating an object that holds a value n = 15 and has a function that accepts a number and multiplies it by n.
In Java this would look something like this
public class Multiplyer {
private int n;
public Multiplyer(int n) {
this->n = n;
}
public int multiple (int m) {
return n*m;
}
}
Multiplyer myMultiplyer = new Multiplyer(15);
System.out.println( myMultiplyer.multiple(10) );
In the JavaScript however the variable fiveMultiplye does not have to call its method, you simple pass it the required variables and it calls the method and returns for you.
Hope that helps.
In JavaScript, you can have a variable which acts as a function too.
var fiveMultiplyer = createMultiplyer(15);
You are calling a CreateMultiplyer(15) function.
This function returns you another function and that is associated
with the fiveMultiplyer var.
var x = fiveMultiplyer(10);
You are actually invoking the function which was returned in previous step.
hence evaluating the value to 10 * 15 = 150
alert(x);
As explained this returns 150
alert(fiveMultiplyer);
As explained this returns the complete function
returned by createMultiplyer().

Categories