Function in function Javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Task: to write a function foo.
function arg1(a,b) {
return a + b;
}
var x = foo(arg1, arg2);
x(arg3); // return arg2 + arg3
var y = foo(arg1, arg2, arg3);
y(); // return arg2 + arg3
I can't understand how at first var x, y - numbers ( because arg1() return number ), and then x, y - functions. How is it possible?

What you want is higher order function curry, a function that will return another function
function add(a,b) {
return a + b;
}
function curry(fun) {
var args = [].slice.call(arguments);
args.shift();
return function() {
return fun.apply(null, args.concat([].slice(arguments)));
};
}
x = curry(add, 10, 20);
x();
if you want to add more then two arguments you need to rewrite add function, you can iterate or use another higher order function reduce.
function add() {
[].slice.call(null, arguments).reduce(function(a, b) { return a+b; });
}
Or you can use #PaulS. solution using reduce in your foo function to call it to more then one argument:
function foo(fun) {
var args = [].slice.call(arguments);
args.shift();
return function() {
return args.concat([].slice.call(arguments)).reduce(fun);
};
};
var x = foo(add, 10, 20, 30);
x(30);

Related

How to write a function to evaluate this expression? [duplicate]

A friend of mine challenged me to write a function that works with both of these scenarios
add(2,4) // 6
add(2)(4) // 6
My instinct was the write an add() function that returns itself but I'm not sure I'm heading in the right direction. This failed.
function add(num1, num2){
if (num1 && num2){
return num1 + num2;
} else {
return this;
}
}
alert(add(1)(2));
So I started reading up on functions that return other functions or return themselves.
http://davidwalsh.name/javascript-functions
JavaScript: self-calling function returns a closure. What is it for?
JavaScript: self-calling function returns a closure. What is it for?
I am going to keep trying, but if someone out there has a slick solution, I'd love to see it!
I wrote a curried function whose valueOf() method and function context (this) are bound with the sum no matter how many arguments are passed each time.
/* add function */
let add = function add(...args) {
const sum = args.reduce((acc, val) => acc + val, this);
const chain = add.bind(sum);
chain.valueOf = () => sum;
return chain;
}.bind(0);
/* tests */
console.log('add(1, 2) = ' + add(1, 2));
console.log('add(1)(2) = ' + add(1)(2));
/* even cooler stuff */
console.log('add(1, 2)(3) = ' + add(1, 2)(3));
console.log('add(1, 2, 3)(4, 5)(6) = ' + add(1, 2, 3)(4, 5)(6));
/* retains expected state */
let add7 = add(7);
console.log('let add7 = add(7)');
console.log('add7(3) = ' + add7(3));
console.log('add7(8) = ' + add7(8));
The reason why both mechanisms are required is because the body of add() must use the called function's bound context in order to access the sum of the intermediate partial application, and the call site must use the valueOf() member (either implicitly or explicitly) in order to access the final sum.
There is an article on Dr.Dobs Journal about "Currying and Partial Functions in JavaScript" which describes exactly this problem.
One solution found in this article is:
// a curried add
// accepts partial list of arguments
function add(x, y) {
if (typeof y === "undefined") { // partial
return function (y) {
return x + y;
};
}
// full application
return x + y;
}
function add(num1, num2){
if (num1 && num2) {
return num1 + num2;
} else if (num1) {
return function(num2){return num1 + num2;};
}
return 0;
}
The concept that you're looking for is called currying and it has to do with function transformation and partial function application. This is useful for when you find yourself calling the same function over and over with mostly the same arguments.
An example of implementing add(2)(6) via currying would look something like this...
function add(x,y) {
if (typeof y === 'undefined') {
return function(y) {
return x + y;
}
}
}
add(2)(4); // => 6
Additionally, you could do something like this...
var add6 = add(6);
typeof add6; // => 'function'
add6(4); // => 10
var add = function(){
// the function was called with 2 arguments
if(arguments.length > 1)
arguments.callee.first_argument = arguments[0];
// if the first argument was initialized
if(arguments.callee.first_argument){
var result = arguments.callee.first_argument + arguments[arguments.length - 1];
arguments.callee.first_argument = 0;
return result;
}else{// if the function was called with one argument only then we need to memorize it and return the same function handler
arguments.callee.first_argument = arguments.callee.first_argument || arguments[0];
return arguments.callee;
}
}
console.log(add(2)(4));
console.log(add(2, 4));
An extended solution which depends on the environment:
function add(){
add.toString = function(){
var answer = 0;
for(i = 0; i < add.params.length; i++)
answer += add.params[i];
return answer;
};
add.params = add.params || [];
for(var i = 0; i < arguments.length; i++)
add.params.push(arguments[i])
return add;
}
console.log(add(2)(4)(6)(8))
console.log(add(2, 4, 6, 8));
We can use the concept of closures which is provided by Javascript.
Code snippet:
function add(a,b){
if(b !== undefined){
console.log(a + b);
return;
}
return function(b){
console.log(a + b);
}
}
add(2,3);
add(2)(3);
In general you need to have an agreement whether the function should return a function (for calling with more arguments) or the end result. Imagine the add function would have to work like this as well:
add(1, 2, 3)(4, 5) // -> 15
...then it becomes ambiguous, because you might want to call again:
add(1, 2, 3)(4, 5)(6) // -> 21
...and so add(1, 2, 3)(4, 5) should have returned a function, and not 15.
You could for instance agree that you have to call the function again, but without arguments, in order to get the numeric result:
function add(...args) {
if (args.length === 0) return 0;
let sum = args.reduce((a, b) => a+b, 0);
return (...args) => args.length ? add(sum, ...args) : sum;
}
console.log(add()); // 0
console.log(add(1,2,3)()); // 6
console.log(add(1,2,3)(4,5)()); // 15
console.log(add(1,2,3)(4,5)(6)()); // 21
One may think that he/she has to invoke the same function two times, but if you think deeply you will realize that the problem is pretty straight forward, you have to invoke the add function one time then you need to invoke what ever the add function returns.
function add(a){
return function(b){
return a+b;
}
}
console.log(add(20)(20));
//output: 40
you can return function as many as time you want. suppose for y = mx+c
const y= function (m){
return function(x){
return function (c){
return m*x+c
}
}
}
console.log(y(10)(5)(10));
//out put: 60

Simple Callback to Promise Conversion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a simple callback example (more like pseudo-code) where values are summed up or multiplied based on the first function parameter.
This is not like a real-life example. Imagine that the task/calculation inside of functions takes some time (like for e.g. calculating the number of stars in the universe). But if we put this aside, the pattern/template with callback looks like this: 
let sum = function(a, b) {
return a + b;
}
let mul = function(a, b) {
return a * b;
}
let dne = function(a, b) {
return 'it does not exist';
}
let doCalculation = function(route) {
switch(route) {
case 'sum':
return sum;
case 'mul':
return mul
default:
return dne
}
}
console.log(doCalculation('sum')(3, 4)) //7
Could this be refactored with Promises in a similar way and if it could be done, could it be done simpler.
You can just convert the functions into async functions/promises.
Some good documentation about that can be found here .
But I guess you also want to simulate some delay. So I added additional function for that (it might help with understanding).
const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
const sumWithDelay = async (a, b) => {
console.log("Delay started")
await sleep(3000)
console.log("Delay ended")
return a + b;
}
const sum = async (a, b) => {
return a + b;
}
const mul = async (a, b) => {
return a * b;
}
let dne = async function() {
return 'it does not exist';
};
let doCalculation = function(route) {
switch (route) {
case 'sum':
return sum;
case 'sumWithDelay':
return sumWithDelay;
case 'mul':
return mul;
default:
return dne;
}
};
doCalculation('sumWithDelay')(2, 2).then(res => console.log(res)); //4
doCalculation('sum')(3, 4).then(res => console.log(res)); // 7
doCalculation('mul')(3, 4).then(res => console.log(res)); // 12
doCalculation('dne')(3, 4).then(res => console.log(res)); // it does not exist
The output will be:
Delay started
7
12
it does not exist
Delay ended
4
You can see that the "sum with delay" has been executed last (after 3 sec).
let sum = function(a, b) {
return a + b;
};
new Promise(function(resolve, reject) {
resolve(sum(1, 2));
}).then(function(previousSum) {
return previousSum + sum(3, 4);
}).then(function(previousSum) {
document.body.innerHTML = previousSum + sum(5, 6);
});

How to make a general function in javascript that calculates sums of the forms: sum(a)(b)(c) .... (s) [duplicate]

This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
Closed 2 years ago.
I am stuck with this problem: I want to write a function in javascript named sum that sums the subsequent arguments like this:
sum(1)(2)= 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10,
and so on. I wrote this code
function sum(a) {
let currentSum = a;
function f() {
if (arguments.length == 1) {
currentSum += arguments[arguments.length - 1];
return f;
} else {
return currentSum;
}
}
f.valueOf = () => currentSum;
f.toString = () => currentSum;
return f;
}
This code works fine if I put empty parentheses at the end of the call like this: sum(1)(2)(3)() = 6 . Is there any way to modify the code so that I can get rid of the empty parentheses?
I appreciate any help. Thanks in advance.
No, you cannot unfortunately. When you supply a number as an argument, the function sends back another function, so you can run it again. Basically, your code needs 'to know' when you are done adding numbers and want to get a number back:
function sum(a) {
let currentSum = a;
function f() {
// In this case we are adding a number to the sum
if (arguments.length == 1) {
currentSum += arguments[arguments.length - 1];
return f;
// In this case we are returning the sum
} else {
return currentSum;
}
}
f.valueOf = () => currentSum;
f.toString = () => currentSum;
return f;
}

How to add the function n number of arguments in Javascript? add(3)(8)(6)(10) [duplicate]

This question already has answers here:
Variadic curried sum function
(19 answers)
How to curry a function across an unknown number of parameters
(7 answers)
Closed 4 years ago.
I need to add the function n number of arguments. Example : add(3)(8)(6)(10).
if it is only 2 arguments we can add the code like this. add(4)(5)
function add(x){
return function(y){
return x+y;
}
}
add(4)(5)
if it is n number of arguments of how can we do this?
The closer I can get to what you asked is this;
function add(x){
var next = function(y){
return add(x + y)
}
next.result = x
return next
}
console.log(add(4)(5).result)
console.log(add(4)(5)(1)(5).result)
console.log(add(3).result)
Here is a slightly different approach using objects, and IMO it is a lot more readable then add(1)(2)(3) since it is clear what operation you are performing in the subsequent steps. Also, this approach allows for extending with more operations, like minus for example.
class Add {
constructor (value) {
this.value = value
}
add (anotherValue) {
return new Add(this.value + anotherValue)
}
result () {
return this.value
}
}
function add (value) {
return new Add(value)
}
var result = add(3).add(5).add(10).result()
console.log(result) // 18
If n is not known beforehand, I can say categorically it's not possible. If n is fixed, you can do something like (say, n is 4):
const add = first => second => third => fourth => first + second + third + fourth.
If you want to let n be flexible, your best bet is this
const add = (...additives) => {
let result = 0;
for (const additive of additives) {
result += additive;
}
return result;
}
As Ryan suggested in his comment : add(3)(8)(6)(10) is impossible.
Try this work around :
function add() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum = sum+arguments[i];
}
return sum;
}
var res = add(3, 8, 6, 10);
console.log(res);

Mathematics functions by string, JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm looking for a function that return me a mathematic function following those examples:
The_Function_I_Need("x^2") = function(x) { return math.pow(x, 2) }
The_Function_I_Need("x*2+5") = function(x) { return 2*x+5 }
The_Function_I_Need("x+y") = function(x, y) { return x+y }
And more..
var The_Function_I_Need = {
"x^2": function(x) {
return Math.pow(x, 2);
},
"x*2+5": function(x) {
return 2 * x + 5;
},
"x+y": function(x, y) {
return x + y;
}
}
console.log(The_Function_I_Need["x^2"](4))
console.log(The_Function_I_Need["x*2+5"](4))
console.log(The_Function_I_Need["x+y"](2, 4))
The Javascript eval() function can evaluate a string as an expression.
To follow your example, you could just use eval("x^2").
Reference: http://www.w3schools.com/jsref/jsref_eval.asp

Categories

Resources