javascript inline function - what are the results? - javascript

What does this function return? I'm not familiar with this nomenclature.
let x = 2;
let y = 8;
const a = function(b) { return function(c) { return x + y + Math.abs(b) + c; } };
// Statement will go here
const fn = a(x);
For the above function, I understand the x+y part, but what is the b and c referred to in the second half? Is a(x) calling const a?
The only thing I found that refers to similar nomenclature is function x y a b in javascript, but the discussion doesn't talk about how to find what is returned. Maybe I'm not searching for the right thing and that's why my search only returned one thing that is similar.

a is the result of a function that accepts an argument, b. That function returns another function that accepts an argument c and returns x + y + c plus absolute value of b.
let x = 2;
let y = 8;
const a = function(b) {
console.log({
b
});
return function(c) {
console.log({
c
});
return x + y + Math.abs(b) + c;
}
};
// Statement will go here
const fn = a(x);
fn(12) // will have b=2 and c=12

It seems like a function pointer. function(b) accepts the parameter x that was passed into the function pointer a, this function pointer references function(b) but unlike normal functions which immediately returns a value, function(b) returns another function function(c) which ofcourse accepts one parameter and that parameter should be filled out when const fn was invoked.
My theory is that when you call fn for example fn(3) then you will get a result equivalent to 2 + 8 + Math.abs(2) + 3;
Without const fn you could also invoke a like a(2)(3) which I believe will yeild the same result.
Hope this helps.

What you see here is called currying, something related, but different from partial application.
The point is to break down a function call taking multiple arguments into multiple function calls taking single arguments.
In this case, a is a function that returns a function that returns the result of adding x, y, the absolute of b (coming from the call to a) and c (coming from the call to the return value of a).

Related

how do Higher Order function understand a variable which is nod fed through function argument?

I'm trying to understand the mechanism of higher order function in JavaScript.
The example I read from eloquent JavaScript is as below.
function greaterThan(n){
return m=>m>n;
}
const greaterThan10=greaterThan(10);
console.log(greaterThan10(11));
I was wondering how do JS automatically recognizes the variable 'm' which wasn't passed to the function as a second variable in a higher order.
I assumed that any variable defined in a higher order function is reserved for the higher order.
Then I tested it out doing like below.
function greaterThan(n){
console.log(m)
return m=>m>n;
}
It throws an error which means my assumption was wrong.
How do JS prepare itself in a higher order function as it does in the first example.
The code seems like it prepared itself saying
" m is not a parameter passed by its function, however it is going to be passed later on in a higher order."
How did it prepared itself for the higher order function? and why my trial (the second approach) is not working?
Your code annotated below:
function greaterThan(n){
console.log(m); // At this point the below function doesn't exist and has not been called yet
return m => m > n; // You're returning a function here with a parameter named m;
}
When you call greaterThan(10) you're getting a function, which needs two inputs to return a result:
m which resolves when you further call the function returned by greaterThan(10)
n which is is a reference to the greaterThan parameter. It is kept alive (not destroyed by the garbage collector) thanks to the JavaScript's closure mechanism
m in this case is the parameter of the lambda function which is returned by greaterThan.
function greaterThan(n) {
// This is lambda function which uses n from the greaterThan function and has m as a parameter
return (m) => m > n;
}
const greaterThan10 = greaterThan(10);
// This equals to this:
const greaterThan10 = (m) => m > 10;
// Which equals to this:
function greaterThan10(m) {
return m > 10;
}
function greaterThan(n){
return m=>m>n;
// here u are actually returning a arrow fn which will take m as paramater
}
const greaterThan10=greaterThan(10);
// the returned fn reference will be assigned to greaterThan10
// greaterThan10 = m => m>11
console.log(greaterThan10(11));
// here u are passing 11 as a paramater to the arrow fn which u are returning
U are trying to log m before u send the parameter m

Currying function with unknown arguments in JavaScript

In a recent interview, I was asked to write a function that adds numbers and accepts parameters like this:
add(1)(2)(3) // result is 6
add(1,2)(3,4)(5) // result is 15
The number of parameters is not fixed, and the arguments can be either passed in sets or individually.
How can I implement this add function?
Given your examples, the number of parameters is fixed in some ways.
As #ASDFGerte pointed out, your examples seem to return the result after three invocations. In this case a simple implementation without introducing terms like variadic and currying could be
function add(...args1){
return function(...args2){
return function(...args3){
return args1.concat(args2).concat(args3).reduce((a,b)=>a+b)}}}
console.log(add(1)(2)(3))
console.log(add(1,2)(3,4)(5))
Every invocation accepts a variable number of parameters.
However it would be nice to generalize the construction of this nested functions structure and you can accomplish that with currying.
But if you want to allow an arbitrary number of invocations, when you should stop returning a new function and return the result? There is no way to know, and this is a simple, unaccurate and partial explanation to give you the idea of why they said you cannot accomplish what they asked you.
So the ultimate question is: is it possible that you misunderstood the question? Or maybe it was just a trick to test you
Edit
Another option would be to actually invoke the function when no arguments are passed in, change the call to add(1)(2)(3)()
Here an example recursive implementation
function sum (...args) {
let s = args.reduce((a,b)=>a+b)
return function (...x) {
return x.length == 0 ? s : sum(s, ...x)
};
}
console.log(sum(1,2)(2,3,4)(2)())
At every invocation computes the sum of current parameters and then return a new function that:
if is invoked without parameters just return the current sum
if other numbers are passed in, invokes recursively sum passing the actual sum and the new numbers
I'm a bit late to the party, but something like this would work (a bit hacky though in my opinion):
const add = (a, ...restA) => {
const fn = (b, ...restB) => {
return add([a, ...restA].reduce((x, y) => x + y) + [b, ...restB].reduce((x, y) => x + y))
};
fn.valueOf = () => {
return [a, ...restA].reduce((x, y) => x + y)
};
return fn;
}
This function returns a function with a value of the sum. The tests below are outputing the coerced values instead of the actual functions.
console.log(+add(1,2)(3,4)(5)); // 15
console.log(+add(1)) // 1
console.log(+add(1)(2)) // 3
console.log(+add(1)(2)(3)) // 6
console.log(+add(1)(2)(3)(4)) // 10
Since it's a currying function, it will always return another function so you can do something like this:
const addTwo = add(2);
console.log(+addTwo(5)); // 7
using reduce and spread it can be done as below
function calc(...args1){
return function (...args2){
return function (...args3){
let merge = [...args1, ...args2, ...args3]
return merge.reduce((x ,y)=> x + y) ;
}
}
}
let sum = calc(10)(1)(4);
console.log("sum",sum);
They probably wanted to know how comfortable you were with "javascript internals", such as how and when methods like Function#toString and Function#valueOf, Function#[Symbol.toPrimitive] are called under the hood.
const add = (...numbers) => {
const cadd = (...args) => add(...args, ...numbers);
cadd[Symbol.toPrimitive] = () => numbers.reduce((a, b) => a + b);
return cadd;
}
console.log(
`add(1,2)(3,4)(5) =>`, add(1,2)(3,4)(5),
); // result is 15
console.log(
`add(1,2) =>`, add(1,2),
); // result is 3
console.log(
`add(1,2)(5)(1,2)(5)(1,2)(5)(1,2)(5) =>`, add(1,2)(5)(1,2)(5)(1,2)(5)(1,2)(5),
); // result is 32

How does JavaScript pass values to a function expression within a declaration?

I'm working through Head First JavaScript and have an example:
function addN(n) {
var adder = function(x) {
return n + x;
};
return adder;
}
var add2 = addN(2);
console.log(add2(10));
console.log(add2(100));
addN(2) gets assigned to add2, but nothing gets assigned to the x. However, upon running the code, the arguments 10 and 100 clearly get passed to the x. How does JavaScript know to pass the 10 and 100 to the x value?
When you do this:
var add2 = addN(2);
The variable add2 is now effectively this:
function(x) {
return 2 + x;
}
Because that function itself is the return value of addN(). (Note that in JavaScript a function is a value that can be assigned to a variable like any other value.)
So when you further do this:
add2(10);
You are passing 10 to that function, so x will be 10.

Javascript Nested Function Evaluation

Hi I am confused with this Javascript function:
var currying = function(a) {
return function(b){
return function(c){
return function(d){
return a + b /c * d;
};
};
};
};
var a = currying(4)(8);
var b = a(2)(6);
console.log(b);
It outputs 28 but I am not sure how did Javascript evaluated the function. I also have learned that a = 4, b = 8, c = 2 and lastly d = 6. Thank you for somebody that will be able to explain the function.
When you use currying you are writing a function that takes one argument, that will return a function taking the next argument until all arguments are supplied.
In this case you need to call the returned function 4 times until you get to the last function and evaluate all the arguments.
This is good because you can pass in arguments at different times during the execution of your code and you can create new functions with arguments already set within the closure of the final functions. eg.
const fourPlusTwo = currying(4)(2)
now you can use the new function fourPlusTwo anywhere in your code and you will have those arguments baked in the closure of the remaining two functions.
The code you have is a non standard example but maybe if you needed to calculate tax throughout your app you could do something like.
const inclusiveTax = rate => amount => {
return '$' + (amount * (rate / (100 + rate))).toFixed(2)
}
const norwayIncomeTax = inclusiveTax(60.2)
const strayaIncomeTax = inclusiveTax(32.5)
const muricaIncomeTax = inclusiveTax(31.5)
console.log(
norwayIncomeTax(50000),
strayaIncomeTax(50000),
muricaIncomeTax(50000)
)
Using just one function you have curried the tax rate for 3 separate countries and returned functions waiting for the amount.
You should know the difference between function object and function call.
like: var a = function(v){return v + 1;} a is a function object. Then a(2) invokes function a.
Try to understand the procedure step by step.
currying is a function which return another function.
so currying(4) returns a function(a is given value 4):
function(b){
return function(c){
return function(d){
return 4 + b /c * d;
};
};
};
};
then currying(4)(8) also is 'var a' returns another function:
function(c){
return function(d){
return 4 + 8 /c * d;
};
};
};
invoking a(2) returns a function object:
function(d){
return 4 + 8 / 2 * d;
};
};
finally a(2)(6) returns 4 + 8 / 2 * 6 which is 28.
This is kind of lexical scoping called Closures
Basically: A closure is a function within function that has access to all parent's variables and parameters. As every parameter in javascript is by default passed by reference, it can even modify parent's variables so you can later execute parent function to see the changes. The great example is jquery's ready function that wraps all other functions within.
You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
This is a very convoluted example of currying - hence the name of the main function.
Currying originates in the field of functional programming and to fully understand it I would suggest that you do some reading, especially as it is implemented in javascript.
To give you some pointers:
In the line:
var a = currying(4)(8);
the first function is called with a parameter of 4; the result of that function call is another function which is then called immediately with a parameter of 8.
Ultimately, all that happens is that the line:
return a + b / c * d;
is executed with the values 4, 8, 2 and 6 for each of the respective variables.
Normal arithmetic rules are applied to give you an answer of 28 (divide first, then multiply and finally add).

Optimize custom Object Property in Array with Javascript

Look at the 3 lines of code within this Javascript function. Assume that y will always be a String:
function example(x, y) {
var s = {};
s[y] = x;
return s;
}
Bearing in mind the following:
Without wrapping it further within a function
Without using ;
Is it possible to condense the 3 lines of code into one?
Yes, with a little ugly code:
function example(x, y, s) {
return (s = {})[y] = x, s;
}
The extra parameter s is not passed into the function, it's only there to be declared as a variable, so you don't need the extra line var s;. (If you don't declare it locally it becomes a global variable, which is bad practice.)
The value of the assignment s = {} is what's assigned, so you can make the assignment and then continue using the value in the expression.
The comma operator returns the last value, e.g. (1,2) returns the value 2. That way you can add , s to the expression to make it return s.
Edit:
Another variation is using s as a variable in a for loop, and exit out of the loop:
function example(x, y) {
for(var s = {}; s[y] = x, true;) return s;
}
Is using function cheating? :)
function example(x, y) {
return new function () { this[y] = x; };
}
There is always evil eval:
function example(x, y) {
return eval('({' + y + ':"' + x + '"})');
}
But I still don't see the point in this.

Categories

Resources