JavaScript Function Calculator - javascript

I have so far:
function func(f,x) {
alert(f(x));
}
func(function(x) {return x*x;},2);
This works, but i am thinking that passing function(x) {return x*x;}, is excessive and I could just pass x*x, as the idea is that I can supply (pretty much) any function.
I have tried:
function func(f,y) {
g=function() {return f;};
alert(g(y));
}
func(x*x,2);
amongst others, but I can't get it to work. Perhaps if I passed 'x*x' as a string..?

You're correct that the syntax is excessive, but for ES5 and before, that's just how it is.
However, in ES6 you can use the new "arrow function" lambda syntax:
func(x => x * x, 2);
See http://www.es6fiddle.net/i4o5uj2l/
FWIW, the above func isn't great since it only supports unary functions, i.e. those taking a single parameter. You could expand func to use ES6 "spread arguments":
function func(f, ...args) {
console.log(f.apply(this, args));
}
func((x, y) => x * y, 3, 7);
> 21

Well I have a way to do that using eval here http://jsfiddle.net/q5ayoszy/
function func(f,y) {
g=function()
{ x=y;
return eval(f);
};
alert(g(y));
}
func('x*x',2);
Note : I pass the expression as a string and then use it inside the function.
You just need to assign the value of y to the variable x inside the function so the eval evaluates correctly

The only way to do that with a string is by using the infamous eval: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
var x = 2;
var y = eval("x * x"); //y = 4
But using eval is almost always a very bad idea.

You could use currying to break down the process into smaller functions:
function multiply(x) {
return function() {
return x*x;
}
}
var bytwo = multiply(2);
bytwo(); // 4

Related

JavaScript - How to modify 'variable' inside function so that it does not revert to original value after function termination?

I have a script like this:
function changeValue(x){
x = 30;
}
let a = 3;
changeValue(a);
console.log(a);
The above code outputs 3, but the expected output is 30. Now I'm aware why this is happening, but how do I modify my code so that the changes made do not revert after the changeValue function ends?
I have read that there are no explicit pointers in JS and I don't want to alter the value using the global variable name or by using the object approach. Is there any other way to solve the problem?
Thank you
The best way would be to use return, because x isn't an object, it's just a variable. It is discarded after the function.
Using Return:
function changeValue(x){
return 30;
}
let a = changeValue(3);
changeValue(a);
console.log("Output Is:", a);
In JavaScript, all primitive types (integers, floats, etc) are passed by value, so as other people said, for your specific use case, it's better to return the value like this:
function returnValue(x) {
return x * 10
}
let a = 3;
a = returnValue(a);
console.log(a);
However, if you really want to change the argument and NOT return, you need to do it with pass by reference. As I said above, it's not possible with primitive data types but is possible with objects:
function changeValue(x) {
x.value = x.value * 10;
}
let a = { value: 3 };
changeValue(a);
console.log(a.value);

Modify arrow function javascript [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 6 years ago.
I have the following arrow function
if( rowCheckStatuses.reduce((a, b) => a + b, 0) ){}
rowCheckStatuses is an array of 1's and 0's, this arrow function adds them all up to produce a number. This number acts as a boolean to determine whether or not there is at least one "1" in the array.
The issue is, I don't really understand how arrow functions work, and my IDE thinks it's bad syntax and refuses to check the rest of my document for syntax errors.
How would I go about converting this to a regular function to alleviate both issues?
An arrow function can usually be converted by replacing
(<args>) => <body>
with
function(<args>) { return <body>; }
So yours would be
rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0)
There are exceptions to this rule so it's important that you read up on arrow functions if you want to know all of the differences. You should also note that arrow functions have a lexical this.
You can refactor it as:
if( rowCheckStatuses.reduce(function(a, b){return a + b}, 0)
The initial accumulator isn't necessary (unless you expect the array to be empty sometimes), it could be:
if( rowCheckStatuses.reduce(function(a, b){return a + b})
This number acts as a boolean to determine whether or not there is at least one "1" in the array
It might be faster (and clearer) to use:
if( rowCheckStatuses.some(function(a){return a == 1}))
which will return true if there are any 1s in rowCheckStatuses and will return as soon as one is encountered. Another alternative is indexOf:
if( rowCheckStatuses.indexOf(1) != -1)
Lots of alternatives.
Replacing arrow functions with regular functions is usually unproblematic:
var f = x => y;
var g = function(x) { return y; }
Or, in your specific example:
rowCheckStatuses.reduce((a, b) => a + b, 0);
rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0);
However, be aware of the exceptions:
Arrow functions don't bind a this value. Accessing this in an arrow function might thus return the value of the enclosing execution context's this:
function MyClass() {}
MyClass.prototype.f = () => this;
MyClass.prototype.g = function() { return this; }
myClass = new MyClass();
console.log(myClass.f()); // logs `Window`
console.log(myClass.g()); // logs `myClass`
Arrow functions also don't have access to a local arguments object. Accessing arguments in an arrow function might e. g. return the arguments of an enclosing function:
function test() {
var f = () => arguments;
var g = function() { return arguments; }
console.log(f()); // logs test's arguments
console.log(g()); // logs g's arguments
}
test('x');
The same holds for new.target and super. See also What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?

Detecting Changes in a Javascript Function's Code

I need to check if a javascript function has been modified by someone overwriting its prototype, or some other way.
For example:
var calc = function(x,y) { return x * y; }
How can I get the code for calc (function(x,y) { return x * y; }) and save it as a string.
I tried:
calc.prototype.toString
calc.toString
But that seems to do something entirely different, it always returns:
toString() { [native code] }
Function.prototype.toString is a function, you're looking at the code of toString rather than your function:
calc.toString()
Is what you're looking for.

Javascript - Issue with Arrow Function

I'm beginner with Javascript and my teacher gave me this code :
var z = (x=>(y=>2*y)(x)+3)(5);
(Sorry for my English, I'm a French guy with a bad level of English ^^)
I have to re-write this code with simple functions but I'm not sure of myself.
For me, I can re-write this code like :
var x = 5;
var y = 2 * x;
var z = y + 3;
But, it's not re-write with simples functions.
My question is : can you help me to understand how arrow function works in this case and give me an idea how to re-write this code with simple functions.
Arrow functions that have a => b form implicitly return b when called. You can imagine them like:
function (a) { return b }
Additionally, your code sample is wrapped in () and immediately invoked, pattern known as the Immediately Invoked Function Expression (IIFE):
(a => b)(3)
which is the same as
(function (a) { return b })(3)
Where both functions get defined and invoked immediately, hence the name.
Now all you have to do is use these two ideas, implicit returns and IIFEs for arrow functions, to re-write your example as plain functions with explicit returns and regular IIFEs.
In other words:
Add return statements where they are assumed to exist (implicit in arrow functions)
Add function() around each arrow function's arguments.
Here's what is happening in your code sample in plain English:
Pass 5 into an IIFE which takes x
Pass that x down to another IIFE which takes y
Return 2 * y from the second IIFE
Add 3 to what was return from second IIFE
Return result from the first IIFE
Or as a math formula:
z = x = (2 * y) + 3
We have:
var z = (x=>(y=>2*y)(x)+3)(5);
The arrow function definition says that x=>(....) means (function(x){ return ...})
So
var z = (function(x) {
return (y=>2*y)(x)+3;
})(5);
We have now another arrow function y=>2*y, that means (function(y) { return 2*y}).
So
var z = (function(x) {
return (function(y) {
return 2*y;
})(x) + 3;
})(5);
And that's all.
Remember that (function(){})() it's an anonymous function declaration executed immediately. So at the end, the var z is a simple number.

How can I write a JavaScript function that will call another function passed as a parameter?

I'm trying to write a JavaScript function that will integrate functions using Simpson's Rule. I fully understand the math behind Simpson's Rule, but I'm unsure of how to write a function that will integrate another function. Here's the code I'd like to implement:
integrate = function(leftBound, rightBound, numSubIntervals, expression) {
var a = leftBound,
b = rightBound,
n = numSubIntervals,
myFunc = expression;
/*implementation of simpson's rule..*/
return result;
}
My issue is that I don't know how to pass a mathematical expression (the function to be integrated) as a parameter without doing something like passing it as a string and using eval(), which is not something I want to do. I also don't want to use any third-party libraries. I want to write the function using vanilla JavaScript only. What am I missing here - is there an obvious solution to this?
Functions themselves can be arguments to other functions. For example:
integrate(0,5,10, function(x){
return x*x;
})
This example takes a function that takes a given X and squares it. Within integrate, you would call this function for given intervals of x to integrate this function using Simpson's rule.
Within integrate, the syntax for calling a function passed to it is:
var point = expression(x);
Where x is the value passed to the function named expression, and point is the return value of expression.
Here's my answer-version of my comment. You can pass the function as parameter and then call it from inside.
integrate = function(leftBound, rightBound, numSubIntervals, expression) {
var a = leftBound,
b = rightBound,
n = numSubIntervals,
myFunc = expression;
/*implementation of simpson's rule..*/
result = (b-a)/6 * (expression(a) + 4*f* ... );
return result;
}
var toIntegrate = function(x){
return 2*x*x*x - 3*x*x + 2*x - 1;
}
integrate(0, 10, 10, toIntegrate);

Categories