I have two functions, One function name is funOne. Another function name is funTwo.
Now I have done simple addition in funOne function and funTwo function.
Now I am trying to pass these funOne and funTwo functions as arguments to another function but output is not coming. Please correct my code to get output.
function fun(funOne, funTwo) {
return (funOne + funTwo)
function funOne(a, b) {
return (a + b)
}
funOne(1, 2)
function funTwo(x, y) {
return (x + y)
}
funTwo(3, 4)
}
console.log(fun)
Is this how you want your result ?
function fun(funOne, funTwo) {
return (funOne + funTwo)
}
function funOne(a, b) {
return (a + b)
}
function funTwo(x, y) {
return (x + y)
}
console.log(fun(funOne(1, 2), funTwo(3, 4)))
1- Putting return as first staement will never execute your other lines.
2- If you log a method in console.log without calling () then it will print whole method
3- QUESTION HEADLINE doesn't makes sense. If that is what you are trying to learn then please look Pass a JavaScript function as parameter
Related
Write a function called specialMultiply which accepts two parameters. If the function is passed both parameters, it should return the product of the two. If the function is only passed one parameter - it should return a function which can later be passed another parameter to return the product. You will have to use closure and arguments to solve this.
Examples:
specialMultiply(3,4); // 12
specialMultiply(3)(4); // 12
specialMultiply(3); // function(){}....
Here specialMultiply takes 2 parameter and if both the parameter is int then will get the multiply of 2 params. otherswise it will return the function
const specialMultiply = (a, b) => {
if (parseInt(a) && parseInt(b)) {
return a*b
}
return (b) => {
return a * b
}
}
console.log(specialMultiply(3));
I am new to JavaScript and have several questions about functional programming.
Here is a statement:
outer(inner(5));
Is it possible to construct function outer in a way that allows it
to capture function inner and its argument 5?
Is it possible to construct function inner in a way that allows it to
pass itself and its argument 5 to function outer?
If the answer to both questions above is no, is it possible to
construct functions outer and inner in a way that allows the former
to capture function inner and its argument 5 or the
latter to pass itself and its argument 5 to function
outer?
I tried:
using the arguments object but to no avail.
function outer (parameter) {
return arguments;
}
function inner (n) {
return n + 1;
}
console.log(outer(inner(5))); // returns Arguments { 0: 6 ... }
using currying but I do not see how it can help me since I am not given the following statement:
outer()(5);
A possible workaround consists in returning an array from inner() composed of on one side the processing function and on the other side the argument.
outer will be able to access both by reading the array.
function outer(arr)
{
var fun = arr[ 0 ];
var arg = arr[ 1 ];
var result = fun(arg);
console.log('inner function is:', fun);
console.log('its argument is:', arg);
console.log('its result is:', result);
return result;
}
function inner(num)
{
return [
function (_num)
{
return _num + 1;
},
num
]
}
console.log(outer(inner(5)));
You could achieve this by letting your inner return a function (foo) which closes over n. You can then let foo return n+1. Then, within your outer function, you can invoke foo to get its return value:
const outer = f => f();
const inner = n => _ => n+1;
console.log(outer(inner(5)));
Alternatively, another possibility would involve changing your return value. You could return an array from inner which contains the original passed through arguments (...arguments) and the returned value (to_return) and then use destructuring assignment to get the passed in argument(s) (n & m) and the returned result:
function outer([result, n, m]) {
console.log("returned from inner: ", result);
console.log("arguments passed into inner: " + [n, m]);
return n;
}
function inner(n, m) {
let to_return = n + 1;
return [to_return, ...arguments];
}
console.log(outer(inner(5, 2))); // returns 5
Note: I added an m argument to demonstrate how you can extend this to multiple arguments
function outer(myFunction, argument) {
if (typeof myFunction !== "function") {
return false;
}
return myFunction(argument);
}
function inner(n) {
return n + 1;
}
console.log(outer(inner, 5));
Just a simple approach. Don’t execute the function inner but pass it as an argument (myFunction). And let the outer function execute it with the given argument.
Question: How would you make this work?
add(2)(5); // 7
add(2, 5); // 7
I am trying to solve the question above:
I know that the first solution uses currying and would be implemented as follows:
var add = functoin(x){
return function (y){
return x+y;
};
};
while the second is jsut your normal function:
var add = functoin(x,y){
return x+y;
};
Is there a way to make both work at the same time?
You can use a higher-order function to wrap other functions with that behaviour.
This kind of function is often called curry, and it comes with many libraries (lodash, for example).
curry returns a new function that checks whether all the expected arguments have been supplied. If they have, it calls originalFunction. If not, it returns a partially applied function,
This implementation uses Function#length to test call arity, so it works with any number of arguments.
function curry (fn) {
return function (...args) {
if (args.length >= fn.length) {
return fn.call(this, ...args)
} else {
return curry(fn.bind(this, ...args))
}
}
}
function add (x, y) {
return x + y;
}
// You can curry any function!
const curriedAdd = curry(add);
console.log(curriedAdd(1, 2)); // 3
console.log(curriedAdd(1)(2)); // 3
console.log(curriedAdd(1)); // a function
You could inspect the amount of arguments passed in and return one or the either depending on it:
function add(a, b) {
if (arguments.length == 2) {
return a + b;
}
return function(b) {
return add(a, b);
}
}
console.log(add(2)(5)); // 7
console.log(add(2, 5)); // 7
"use strict";
function square(x) {
return x * x;
}
function add(square,y) {
return square(4) +y
document.write(square + y)
}
add(4,1);
console.log(add(4,1));
I have to use a function as in the parameter of another function. I am trying to output 17.
Just call it as such:
add(square,1);
you may also want to change
function add(square,y) {
return square(4) +y
document.write(square + y)
}
to be:
function add(square,y) {
document.write(square(4) + y)
return square(4) +y
}
Per Andrew's comment, it might also be a good choice to change document.write calls to be console.log and open the browser console to read results.
Probably easier to visualize if you change the argument name in your function declaration to be more generic but also more identifiable as a function requirement.
The name you use here is not relevant to the name of the function you will actually pass in
function add(func, num) {
document.write(func(4) + num);
return func(4) + num;
}
add(square,1);
Then in another call you might do
add(myOtherCalcFunction, 6);
I'm trying to understand how a function works that is run with two parentheses and two parameters. Like so:
add(10)(10); // returns 20
I know how to write one that takes two params like so:
function add(a, b) {
return a + b;
}
add(10,10); // returns 20
How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?
Any help is appreciated. Literally scratching my head over this.
Thanks in advance!
How could I alter that function so it could be run with one set of parameters, or two, and produce the same result?
You can almost do that, but I'm struggling to think of a good reason to.
Here's how: You detect how many arguments your function has received and, if it's received only one, you return a function instead of a number — and have that function add in the second number if it gets called:
function add(a,b) {
if (arguments.length === 1) {
return function(b2) { // You could call this arg `b` as well if you like,
return a + b2; // it would shadow (hide, supercede) the one above
};
}
return a + b;
}
console.log(add(10, 10)); // 20
console.log(add(10)(10)); // 20
I said "almost" above because just because the add function received only one argument, that doesn't guarantee that the caller is going to call the result. They could write:
var x = add(10);
...and never call the function that x now refers to.
Welcome to the wonderful world of first order functions
In JavaScript, a function can return a function since a function is just another object. A simple implementation is something like:
function add(x){
return function addOther(y){
return x + y;
};
}
This is possible because of closures and first order functions.
This also lets you do partial application, libraries like Ramda utilize this to great extent.
var addThree = add(3)
addThree(5); // 8
To extend what both T. J. Crowder and Benjamin Gruenbaum said, libraries like Ramda (disclosure: I'm one of the authors) allow you to convert a simple function like this:
function add(a, b) {
return a + b;
}
into the style under discussion by wrapping it in a call to a curry function:
var add = R.curry(function add(a, b) {
return a + b;
});
add(3, 5); //=> 8
add(3)(5); //=> 8
var add3 = add(3);
add3(5); //=> 8
The best article I know on this subject is Hugh Jackson's Why Curry Helps. I wrote a more detailed one at Favoring Curry.
Update
Here is a version of curry somewhat simpler than the one in Ramda. It would do the above and quite a bit more, but doesn't do some of the things that Ramda does with placeholder values:
// here is a function that takes a function and returns a curried version
// of it, that is, a version that performs the sort of partial application
// you describe.
var curry = function(fn) {
// first, we detect how many arguments the function has.
var fnArity = fn.length;
var partialApply = function(args) {
// now, let's create a function that's curried
return function () {
// collect the previous args as the partial, and add the new
// ones you just received
var newArgs = (args || []).concat([].slice.call(arguments, 0));
// if we have "enough" arguments, we don't need any more partial
// application and we can call the function.
if (newArgs.length >= fnArity) {
return fn.apply(this, newArgs);
} else { // else we return a partially applied version
return partialApply(newArgs);
}
};
};
return partialApply([]); // a function is itself partially applied with 0 args
};
function add() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
function total() {
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return total;
}
total.toString = function () { return sum };
return total;
}
This will work for any no of arguments and parentheses.
https://medium.com/#imdebasispanda/super-function-with-closure-86a58a9a980b