swap() function for variables's values [duplicate] - javascript

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
I am not able to achieve the desired result for this swap function below, where I want the values printed as 3,2
function swap(x,y){
var t = x;
x = y;
y = t;
}
console.log(swap(2,3));
Any clue will be appreciated !

Your function is swapping the values internally, but the function does not return a value.
The following method returns an array of values in reverse order of what was supplied.
function swap(x, y) {
var t = x;
x = y;
y = t;
return [x, y];
}
console.log(swap(2, 3));
However, you could easily do something like the following snippet, because - based on your supplied code - there seems to be no need to actually swap the values of the arguments.
function swap(x, y) {
return [y, x];
}
console.log(swap(2, 3));

If you don't actually need the values to swap:
function swap (x, y)
{
return [y, x];
}
If you do need the values to swap, but you don't want to declare another variable:
function swap (x, y)
{
x = x + y;
y = x - y;
x = x - y;
return [x, y];
}

Related

Printing curried function doesn't show the captured parameter

If I define a curried function like this:
const gt = x => y => y > x
I would expect gt(5) returns y => y > 5
but gt(5) (or gt(5).toString()) returns y => y > x
How do I get the captured parameter?
I would expect gt(5) returns y => y > 5
That isn't how JavaScript works. The code of the function returned by gt(5) is y => y > x, it's just that that code executes in an environment where the identifer x resolves to a binding that has the value 5 because it's a closure over that environment. toString on functions returns a string version of the source code of the function (or a function declaration around the [ native code ]) (spec), so you still see y => y > x. The string returned by toString doesn't include the environment in which that code runs.
See also:
How do JavaScript's closures work? - here on SO
Closures are not complicated - on my old anemic blog (uses some outdated terminology, I should probably fix that)
As #VLAZ points out in a comment, you can override the default toString on a function to give it the behavior you want. If you don't mind duplication (which almost inevitably leads to maintenance issues):
const gt = x => {
const fn = y => y > x;
fn.toString = () => `y => y > ${x}`;
return fn;
};
console.log(String(gt(5)));
...or if you want to define toString with the same enumerability, etc., as the version on the prototype:
Object.defineProperty(fn, "toString", {
value: () => `y => y > ${x}`,
writable: true,
configurable: true,
});
Doing that in the general case requires a proper JavaScript parser to do the substitution.
It's not possible to just print a variable captured in a closure, however there is a workaround for curry. I will be referring to Brian Lonsdorf's article on Medium Debugging Functional which goes into more details about curry and compose. I heartily recommend reading the article itself, as I will only use the essentials.
Brian Lonsdorf proposes a custom implementation of a general curry function. The original version is taken from an article by Erin Swenson-Healy.
Here is the modified version:
function fToString(f) {
return f.name ? f.name : `(${f.toString()})`;
}
function curry(fx) {
var arity = fx.length;
function f1() {
var args = Array.prototype.slice.call(arguments, 0);
if (args.length >= arity) return fx.apply(null, args);
function f2() {
return f1.apply(null, args.concat(Array.prototype.slice.call(arguments, 0)));
}
f2.toString = function() {
return fToString(fx)+'('+args.join(', ')+')';
}
return f2;
};
f1.toString = function() { return fToString(fx); }
return f1;
}
const gt = curry((x, y) => y > x);
const sum3 = curry((x, y, z) => x + y + z);
const ltUncurried = (x, y) => y < x;
const lt = curry(ltUncurried);
console.log(gt(1)); // ((x, y) => y > x)(1)
console.log(sum3(1)); // ((x, y, z) => x + y + z)(1)
console.log(sum3(1, 2)); // ((x, y, z) => x + y + z)(1, 2)
console.log(sum3(1)(2)); // ((x, y, z) => x + y + z)(1, 2)
console.log(lt(1)); // ltUncurried(1)
(I have modified fToString() to include brackets around f.toString() for better readability)
This is quite flexible as it allows currying any function but also provides better logging of said function. The toString implementation can be modified if required for whatever you deem are the most important details.
const gt = x => y => y > x
gt(1);
If you had pass only 1 argument like gt(1) and if you Check in console, x = 1, y is not available at this time. So the execution context (call stack) will show only the x argument and for the gt() method it will only show the code (y > x).
And here below gives us a hint that gt(1) will first bind x to 1, and return a new function f(y) = y > x = y > 1
You didn't second pass second argument, It means now the function f(y) = 1 + y is executed, and this time, it will check for the y where y is not available at that time. And the argument x’s value 1 is still preserved in the context via Closure.
It's look like same as below closure function :-
function add(x) {
return function (y) {
return y > x
}
}
var d = add(1)(2); ===>>>> true

Uncaught reference, Array not defined in JavaScript Chrome console

In Chrome console, I am getting this error,
Uncaught ReferenceError: operations is not defined
at :1:1
(anonymous) # VM118:1
yet this snippet runs here when I pasted it in.
What am I missing? I am trying to declare 4 functions, and capture them in a variable as an array, and then loop over that array.
function add(x, y) {
return x + y;
}
const subtract = function(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
}
const divide = function(x, y) {
return x / y;
}
//We can store functions in an array!
const operations = [add, subtract, multiply, divide];
//Loop over all the functions in operations
for (let func of operations) {
let result = func(30, 5); //execute func!
console.log(result);
}

How to refactor the method in react?

T want to divide a method into two, so that it can be used by two methods with different arguments.
What am I trying to do?
I have a method named convert_point that takes values x and y based on a click on a canvas and then converts that to x, y and z values as an array.
add_point_at = (x, y) => {
this.props.convert_point([x, y]).then(converted_point => {
let next;
let some_var = this.state.some_var;
if (some_var === undefined) {
this.method1();
next = this.add(this.props.drawings);
some_var = next.paths.length - 1;
this.setState({
some_var: some_var,
draft_point: {x: x, y: y},//seems like this x and y values
needs to replaced as well...
});
} else {
next = this.props.drawings;
this.setState({
some_var: undefined,
});
}
const variable = next.paths[some_var];
next_drawings = this.add_path(
next, converted_point[0], converted_point[1],
converted_point[2]);
this.props.on_drawings_changed(next_drawings);
}).catch(some_method_called);
};
The above method accepts x and y values, so basically it is called by another function like below. Here x and y are, say, 20 and 30 and when given to this.props.convert_point method in add_point_at, the output is say [11.2, -13, 45], so basically converted_point given to the then method is [11.2, -13, 45]:
handle_click = (x, y) => {
this.add_point_at(x,y);
}
This works fine. Now there is a situation where I have x, y and z values already and want to call the add_point_at method… So I divided the add_point_at method as below:
add_point_at = (x, y) => {
this.props.convert_point([x,
y]).then(this.call_another_method).catch(some_method_called);
call_another_method = (converted_point) => {
let next;
let some_var = this.state.some_var;
if (some_var === undefined) {
this.method1();
next = this.add(this.props.drawings);
some_var = next.paths.length - 1;
this.setState({
some_var: some_var,
draft_point: {x: x, y: y},// x and y values are unknown
});
console.log("last statement in if");
} else {
next = this.props.drawings;
this.setState({
some_var: undefined,
});
}
console.log("first statement after else");
const variable = next.paths[some_var];
next_drawings = this.add_path(
next, converted_point[0], converted_point[1],
converted_point[2]);
this.props.on_drawings_changed(next_drawings);
};
So if I have x, y and z values already, I directly call:
this.call_another_method(converted_point);
If I have only x and y values, I call
this.add_point_at(x, y);
…so that this converts x, y to x, y, z values using the this.props.convert_point method.
But after dividing the method, it doesn't work. I don't see any console error. To debug, I tried to add console statements as seen in code above, but it is not logged to the console. Not sure why.
Could someone help me understand where the problem is?
EDIT: i realised that the problem is with the x and y values undefined in the splitted method...how can i refactor this method such that x and y values are replaced with something.

Advantages of using curried functions over a normal function in javascript

Below is a specific use case of using a normal and a curried function. Are there any advantages for using either if you only using two arguments?
//Normal Function
function add(x, y) {
return x + y;
}
//Curried Function
function add1(x) {
return function add2(y) {
return x + y;
}
}
Here's a small example:
let add = (x, y) => x + y;
let addc = x => y => x + y;
// add 5 to every element
result = [1,2,3,4,5].map(x => add(x, 5)) // dirty and tedious
result = [1,2,3,4,5].map(addc(5)) // nice and tidy
In general, curried functions allow to express the logic in a "point-free" style, that is, as a combination of functions, without using variables, arguments and similar constructs.

JavaScript Closures - Program flow [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 5 years ago.
Can anyone explain how this code works?
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
Reference: https://mozilla.org/en/docs/Web/JavaScript/Closures
When you call your makeAdder(5), it returns the reference to a new function.
function(y) {
return x + y;
};
So add5 keeps the reference. After it when you call add5(2), you pass the 2 to the function. In it when it wants to return x + y, it starts to find the variables. Starting from x, it looks and see's that the x is not defined in it and goes to the scope in which inner function was defined ` here
function makeAdder(x) {
return function(y) {
return x + y;
};
}
It see's than x was defined here, because you call and pass x during var add5 = makeAdder(5);. After it goes to find y and finds in it's scope. And after all returns x + y.
The idea is this, every function has a reference to it's creater (where it was defined) and when it doesn't find a variable, it goes to find in it's greater and so till to global scope.
function makeAdder(x) {
return function(y) {
return x + y;
};
}
When you do var add5 = makeAdder(5); the add5 becomes a function which was returnd my makeAdder,
the add5 will be following
function(y){
return 5 + y;
}
so when you do add5(2) it will do 5 + 2 and will return 7;
makeAdder(5)
x => 5 and y is not having value so x+y => 5+0 => 5
var add5 = makeAdder(5);
add5(2);
we have created variable for the function makeadder with x => 5
so now we pass y => 2 and x => 5 so x+y => 5+2 => 7
This property of outer function variable accessible in inner function is called closure property in javascript. Also adding to that y variable is not accessible to outer function.

Categories

Resources