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

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...

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.

Best practice for returning a variable that exists in global scope?

Is the return statement in here unnecessary?
var fahrenheit;
var celsius;
function cToFConvert () {
celsius = temperatureInput.value;
fahrenheit = celsius * (9/5) +32;
console.log(fahrenheit);
return fahrenheit;
}
I can get the fahrenheit value even if I do not use the return statement. Does that mean using a return is redundant if the variable was declared in global scope?
Function and pure function.
The concept to keep a function pure is the idea to use the function without side effects. This means, the function should rely on own parameters and return something which is related to the parameters only.
That means a function should have some input and and some output.
In this case for converting a temperature, you have a value Celsius and want to get the value in Farenheit. This is a good example how to write a function which is resusable for any purpose and could be inserted into a library without changes.
How does it work?
You may think of an input and an output based on the input.
function convertCelsiusToFarenheit(celsius) {
return celsius * 9 / 5 + 32;
}
Now you can use the function with a wanted input and store the output to a variable
var myFarenheit = convertCelsiusToFarenheit(temperatureInput.value);
Or if you like to convert a bunch of values, you could use the function as callback
var myFarenheitData = [-10, 0, 10, 20, 30, 40].map(convertCelsiusToFarenheit);
With this in mind, its is easier to write a multipurpose function.
DON'T USE GLOBAL VARIABLES.
var farenheit;
var celsius;
function cToFConvert () {
celsius = temperatureInput.value;
farenheit = celsius * (9/5) +32;
console.log(farenheit);
return farenheit;
}
You can remove the return statement.
No it is not necessary. Why you use global variable, you will have access to it anywhere and can change it's value anywhere.
For alternate you can do
function cToFConvert(celsiusValue){
return celsiusValue* (9/5) +32;
}
And call like
var fahrenheit = cToFConvert(temperatureInput.value);
Avoid working with variables outside of the method, that would be my suggestion. Pass the variables to the method as parameters and return the result. If you still want to work with the variables outside the method, then the return is redundant because you're already modifying the variable inside the method.
function cToFConvert(celsius) {
return celsius * (9 / 5) + 32;
}
var celsius = 123; //temperatureInput.value;
var farenheit = cToFConvert(celsius);
console.log(farenheit);
Here I think is reductant, but I think this would not be a valid implementation either. Instead you can do:
var cToFConvert = function() {
var celsius = temperatureInput.value;
var farenheit = celsius * (9/5) +32;
console.log(farenheit);
return farenheit;
}
and then
var convertedValue = cToFConvert();
Hope this helps!
Though it is redundant here, both of the approaches differ.
Case 1: You do not use return.
Here, the calling method doesn't expect a value.
Eg. var y=cToFConvert();
`y` will be `undefined`.
Case 2: When you use return.
The calling method expects a value to be returned.
Eg. var y=cToFConvert();
y will have the value farenheit.
Over the two, I personally prefer Case 1, because by looking at the function call, you can clearly say what the function returns. Also as mentioned in other answer, do not use Global variables unless there is no way out.
var farenheit=0, celsius=13; //definded in global space
function cToFConvert () {
farenheit = celsius * (9/5) +32; //using global variables, no need to return
}
function checkFarenheit(){
alert(farenheit); //checking global variable.
}
cToFConvert();
checkFarenheit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: this is not at all good practice as it will be more error prone, use promises or callbacks methods.

passing arguments in constructer function in javascript

function player(){
this.hitpoints =100;
this.attack = function attack(opponent){
opponent.hitpoints -= 10;
}
}
var p1 = new player();
var p2 = new player();
p1.name = "ali";
p2.name = "ahmed";
p1.attack(p2);
alert(p2.name+"has"+p2.hitpoints+"left behind");
The output of the above code is
ahmed has 90 left behind.
But whenever I change my code to p1.attack(p2.name; instead of p1.attack(p2); then it will output the following result:
ahmed has 100 left behind.
Why does it output this result?
I am a beginner in Javascript, I do not really know anything about objects. I simply want to know how arguments should be passed in that particular attack() function.
It is because you're passing an object to the function.
Passing p2.name as a parameter will not work, since p2.name is a property with data type of string.
The operation then goes with the following parameters given:
attack(p2) => p2.hitpoints -= 10
attack(p2.name) => p2.name.hitpoints -=10,
which is not valid because p2.name is not an instance of player.
If you use
p1.attack(p2.name)
then the code will try to substract 10 from p2.name.hitpoints and left p2.hitpoints intact.

Trouble understanding a basic concept in Javascript Higher Order Functions

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()

Categories