JS function which can work with 2 different invocations. - javascript

How to define a function lets say 'add' in Javascript, that will support both of these invocations.
add(5,6)
or
add(5)(6)
both giving the same output, which is 11.

function add(a, b)
if (typeof(b) === "undefined") {
return function (b) { return a + b; };
}
return a + b;
}
or, the logical extension:
function add(a, b)
if (typeof(b) === "undefined") {
return function (b) { return a + b; };
}
return add(a)(b);
}

Related

Arguments Optional - why do I get a string for arguments (2)([3])?

This is a follow up to my questions on the Arguments Optional Challenge in Freecodecamp (see below0:
I have now satisfied 5/6 conditions of the challenge, except for when the input is addTogether(2,([3])), which returns '23' as a string instead of the correct 'undefined'.
If the [3] is an array, and an array is an object, shouldn't my checkNum function work to label that as undefined? Where was the string generated?
my code now:
function addTogether() {
function checkNum(x) {
return typeof x === 'number' ? x : undefined;
}
let num1 = checkNum(arguments[0]);
let num2 = checkNum(arguments[1]);
if (arguments.length === 1) {
if (typeof num1 === 'number') {
let a = num1;
return function (b) {
return a + b;
};
}
return undefined;
}
if (arguments.length > 1) {
if (typeof num1 !== 'number' || typeof num2 !== 'number') {
return undefined;
}
if (typeof num1 === 'number' && typeof num2 === 'number');
{
return arguments[0] + arguments[1];
}
}
}
THANKS
//original question below:
I am stuck on the freecodecamp problem Arguments Optional.
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional
In researching the problem, there have been multiple references to the following code-block, but I just can't get my head around what it means:
if(arguments.length==1){
if (typeof a == "number"){
return function(b){
if (typeof b == "number"){
return a + b;
}
};
}
}
I understand up to the 'return function(b)' part, then my brain melts.
If someone could please explain it as if to a 6-year-old, this noob would really appreciate the help.
This is quite common practice to return a function instead of a value.
When the outer function (which is supposed to do addition) is called with one argument, instead of doing addition (can't do) it is returning a function. When that function is called subsequently with a number parameter it executes the function b and does the sum.
Let us say the outer function name is add() so it can be triggered the following ways:
add(10, 15); // 25
var f = add(20);
f(18) // 38
add(4)(6) // 10
Full example:
function add(a, b) {
if (arguments.length == 1) {
if (typeof a == "number") {
return function (b) {
if (typeof b == "number") {
return a + b;
}
};
} else {
return "undefined";
}
} else if (arguments.length == 2) {
if (typeof a == "number" && typeof b == "number") {
return a + b;
} else {
return "undefined";
}
} else {
return "undefined";
}
}
console.log(add(10, 15));
var f = add(20);
console.log(f(18));
console.log(add("xyz"));
console.log(add(10, "5"));
console.log(add(4)(6));
We can declare functions in 2 ways, the regular way:
function test(){
}
or the interesting way
let test = function(){
}
in this case, the function is returning a function
see here:
function returnfunction(){
return function(b){
if (typeof b == "number"){
return a + b;
}
}
}
let x = returnfunction()
So, x is the return value of returnfunction, which is
function(b){
if (typeof b == "number"){
return a + b;
}
}
So similar to above,
x = function(){
//...
}

How to write a function which can accept one or more arguments and send back addition

I have to call function in below way
sum(3)(2)
My function is:
sum(a,b) { return a + b }
Take a look at Currying concept
let sum = (a) => (b) => a + b
console.log(sum(1)(3)) // 4
you can try out this approach
function sum(x, y) {
if (y !== undefined) {
return x + y;
} else {
return function(y) { return x + y; };
}
}
To understand it better https://www.toptal.com/javascript/interview-questions

My javascript Program comparing 2 numbers keeps returning error

I am trying to write a function that takes 2 numbers and returns the bigger one but I keep getting error module.js540 throw err.
function largerThan(a,b){
if(a > b) {
return a;
}else {
return b;
}
}
var biggerNumber = largerThan(1,2);
console.log(biggerNumber)
return var biggerNumber = a is a syntax error
You're looking for:
return a
function largerThan(a,b){
if(a > b) {
return a;
}else {
return b
}
}
var biggerNumber = largerThan(1,2);
console.log(biggerNumber)
try this
You are mixing a 'variable declaration' statement and a 'return' statement.
The code should look like this:
function largerThan(a,b) {
if(a > b) {
return a;
}else {
return b;
}
}
var biggerNumber = largerThan(1,2);
If b is the larger number, then the function will return the value in b. The statement "var biggerNumber = largerThan(1,2)" will store the value that the function returned to your variable.

closure in javascript with multiple empty calls to sum function

I faced this question in one interview. I did not get how to solve this.
Question: Write a sum function which will add 2 numbers, but numbers can be passed to a function in following ways:
sum(3)(4) // answer should be 7
sum(3)()(4)//answer should be 7
sum(3)()()()()(4) //answer should b 7
I can solve first function using closure, in fact for the second function also I can check the arguments and if arguments length is zero I can again make a call to sum to except next parameter.
But how to make it generic ? Means even your first parameter and last parameter has 'N' number of calls & those can be empty or parameterized, it should return sum.
Recorded a video how to solve it:
https://youtu.be/7hnYMIOVEg0
Text answer:
function sum(numberOne) {
return function innerSum(numberTwo) {
if (typeof(numberTwo) === 'number') {
return numberOne + numberTwo;
}
return innerSum;
}
}
Output:
sum(3)(4); => 7
sum(5)()()(10); => 15
Basically, you need to return inner function (innerSum) up until you receive a value - then you return number.
You could also choose another name - like _sum(), or addToFirstNumber() for your method.
You can always return a function from within a function:
let a;
function sum(value) {
if (typeof value !== "number") {
return sum;
}
if (typeof a !== "number") {
a = value;
return sum;
}
let result = a + value;
a = null;
return result;
}
see https://jsfiddle.net/d9tLh11k/1/
function sum(num1) {
return function sum2(num2) {
if(num2 === undefined) {
return sum2;
}
return num1 + num2;
}
}
console.log(sum(4)()()()(3)); // -> 7
Or in ES6:
const add = num1 => num2 => num2 === undefined ? add(num1) : num1 + num2;
console.log(add(4)()()()()()(3)); // -> 7
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function () {
return n;
};
return func;
}
console.log(+add(1)(2)(3)()()(6));
I have already given answer of this question Here
but according to your question I have modified that
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function () {
return n;
};
return func;
}
console.log(+add(1)(2)(3)()()(6));
Run code like that
console.log(+add(1)(2)(3)()()(6));
This should do it
function sum(num1) {
if (arguments.length === 0){
return sum;
}
return function innerSum(num2) {
if (arguments.length > 0){
return num1 + num2;
}else{
return innerSum;
}
}
}
You can do this in a number of ways, but mostly you'll want named recursion. That is, you can have something like:
sum = start => (...args) => args.length? args[0] + start : sum(start)
but it might look cleaner to write this as:
function sum(start) {
function out(...args) {
return args.length? start + args[0] : out
}
return out;
}

Javascript functional programming quiz

Here is the problem. I have to implement make function:
var sum = function (a, b) { return a + b; }
var mult = function (a, b) { return a * b; }
//'make' function goes here
var res = make(1)(2)(3)(4);
console.log(res(sum)); //OUTPUT: 10
console.log(res(mult)); //OUTPUT: 24
I have implemented it, but I feel like a little better way still exists. :)
So, here is my solution:
function make(a, arr) {
if (a instanceof Function) { return arr.reduce(a); }
arr = arr || [];
arr.push(a);
return function (b) { return make(b, arr); };
}
You want functions? You can have functions!
function sum(a, b) { return a + b; }
function mult(a, b) { return a * b; }
function diff(a, b) { return a - b; }
function make(x, f) {
if (typeof x === 'function') return f(x);
return function(y) {
return make(y, function(a) {
return f ? a(f(a), x) : x;
});
};
}
console.log(make(1)(2)(3)(4)(sum)); // -> 10
console.log(make(1)(2)(3)(4)(mult)); // -> 24
console.log(make(4)(3)(2)(1)(diff)); // -> -2
Instead of building up an array, this builds up a function that, when given a function, reduces all the elements using that function, from left to right :)
I'm pretty sure this wouldn't qualify as code that anyone would ever want to see in their codebase.
function make(inp, arr) {
if (typeof inp == 'function') {
while(arr.length > 1)
arr.push(inp(arr.pop(), arr.pop()));
return arr[0];
}
if (!arr) arr = [];
arr.push(inp);
return function (inp1) {
return make(inp1, arr);
};
}
Here's a better JavaScript specific solution:
var test = make(1)(2)(3)(4);
alert(test(add)); // ((1 + 2) + 3) + 4 = 10
alert(test(mul)); // ((1 * 2) * 3) * 4 = 24
alert(test(sub)); // ((1 - 2) - 3) - 4 = -8
function make(x) {
if (typeof x !== "function") return foldl([x]);
throw new TypeError("Initial value can't be a function");
}
function foldl(array) {
return function (fx) {
return typeof fx !== "function" ?
foldl(array.concat(fx)) :
array.reduce(fx);
};
}
function add(a, b) { return a + b; }
function mul(a, b) { return a * b; }
function sub(a, b) { return a - b; }
There are several advantages to this method:
Better error reporting when you write incorrect code like make(add).
Simple functional definition which is easy to read and understand.
If you want foldr then just rename reduce to reduceRight.
Using concat instead of push to preserve original array.
I can't think of a better functional implementation for make.

Categories

Resources