Related
I need a js sum function to work like this:
sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10
etc.
I heard it can't be done. But heard that if adding + in front of sum can be done.
Like +sum(1)(2)(3)(4). Any ideas of how to do this?
Not sure if I understood what you want, but
function sum(n) {
var v = function(x) {
return sum(n + x);
};
v.valueOf = v.toString = function() {
return n;
};
return v;
}
console.log(+sum(1)(2)(3)(4));
JsFiddle
This is an example of using empty brackets in the last call as a close key (from my last interview):
sum(1)(4)(66)(35)(0)()
function sum(firstNumber) {
let accumulator = firstNumber;
return function adder(nextNumber) {
if (nextNumber === undefined) {
return accumulator;
}
accumulator += nextNumber;
return adder;
}
}
console.log(sum(1)(4)(66)(35)(0)());
I'm posting this revision as its own post since I apparently don't have enough reputation yet to just leave it as a comment. This is a revision of #Rafael 's excellent solution.
function sum (n) {
var v = x => sum (n + x);
v.valueOf = () => n;
return v;
}
console.log( +sum(1)(2)(3)(4) ); //10
I didn't see a reason to keep the v.toString bit, as it didn't seem necessary. If I erred in doing so, please let me know in the comments why v.toString is required (it passed my tests fine without it). Converted the rest of the anonymous functions to arrow functions for ease of reading.
New ES6 way and is concise.
You have to pass empty () at the end when you want to terminate the call and get the final value.
const sum= x => y => (y !== undefined) ? sum(x + y) : x;
call it like this -
sum(10)(30)(45)();
Here is a solution that uses ES6 and toString, similar to #Vemba
function add(a) {
let curry = (b) => {
a += b
return curry
}
curry.toString = () => a
return curry
}
console.log(add(1))
console.log(add(1)(2))
console.log(add(1)(2)(3))
console.log(add(1)(2)(3)(4))
Another slightly shorter approach:
const sum = a => b => b? sum(a + b) : a;
console.log(
sum(1)(2)(),
sum(3)(4)(5)()
);
Here's a solution with a generic variadic curry function in ES6 Javascript, with the caveat that a final () is needed to invoke the arguments:
const curry = (f) =>
(...args) => args.length? curry(f.bind(0, ...args)): f();
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1)() == 5 // true
Here's another one that doesn't need (), using valueOf as in #rafael's answer. I feel like using valueOf in this way (or perhaps at all) is very confusing to people reading your code, but each to their own.
The toString in that answer is unnecessary. Internally, when javascript performs a type coersion it always calls valueOf() before calling toString().
// invokes a function if it is used as a value
const autoInvoke = (f) => Object.assign(f, { valueOf: f } );
const curry = autoInvoke((f) =>
(...args) => args.length? autoInvoke(curry(f.bind(0, ...args))): f());
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1) + 0 == 5 // true
Try this
function sum (...args) {
return Object.assign(
sum.bind(null, ...args),
{ valueOf: () => args.reduce((a, c) => a + c, 0) }
)
}
console.log(+sum(1)(2)(3,2,1)(16))
Here you can see a medium post about carried functions with unlimited arguments
https://medium.com/#seenarowhani95/infinite-currying-in-javascript-38400827e581
Try this, this is more flexible to handle any type of input. You can pass any number of params and any number of paranthesis.
function add(...args) {
function b(...arg) {
if (arg.length > 0) {
return add(...[...arg, ...args]);
}
return [...args, ...arg].reduce((prev,next)=>prev + next);
}
b.toString = function() {
return [...args].reduce((prev,next)=>prev + next);
}
return b;
}
// Examples
console.log(add(1)(2)(3, 3)());
console.log(+add(1)(2)(3)); // 6
console.log(+add(1)(2, 3)(4)(5, 6, 7)); // 28
console.log(+add(2, 3, 4, 5)(1)()); // 15
Here's a more generic solution that would work for non-unary params as well:
const sum = function (...args) {
let total = args.reduce((acc, arg) => acc+arg, 0)
function add (...args2) {
if (args2.length) {
total = args2.reduce((acc, arg) => acc+arg, total)
return add
}
return total
}
return add
}
document.write( sum(1)(2)() , '<br/>') // with unary params
document.write( sum(1,2)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)() , '<br/>') // with unary params
document.write( sum(1)(2,3)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)(4)() , '<br/>') // with unary params
document.write( sum(1)(2,3,4)() , '<br/>') // with ternary params
ES6 way to solve the infinite currying. Here the function sum will return the sum of all the numbers passed in the params:
const sum = a => b => b ? sum(a + b) : a
sum(1)(2)(3)(4)(5)() // 15
function add(a) {
let curry = (b) => {
a += b
return curry;
}
curry[Symbol.toPrimitive] = (hint) => {
return a;
}
return curry
}
console.log(+add(1)(2)(3)(4)(5)); // 15
console.log(+add(6)(6)(6)); // 18
console.log(+add(7)(0)); // 7
console.log(+add(0)); // 0
Here is another functional way using an iterative process
const sum = (num, acc = 0) => {
if !(typeof num === 'number') return acc;
return x => sum(x, acc + num)
}
sum(1)(2)(3)()
and one-line
const sum = (num, acc = 0) => !(typeof num === 'number') ? acc : x => sum(x, acc + num)
sum(1)(2)(3)()
You can make use of the below function
function add(num){
add.sum || (add.sum = 0) // make sure add.sum exists if not assign it to 0
add.sum += num; // increment it
return add.toString = add.valueOf = function(){
var rtn = add.sum; // we save the value
return add.sum = 0, rtn // return it before we reset add.sum to 0
}, add; // return the function
}
Since functions are objects, we can add properties to it, which we are resetting when it's been accessed.
we can also use this easy way.
function sum(a) {
return function(b){
if(b) return sum(a+b);
return a;
}
}
console.log(sum(1)(2)(3)(4)(5)());
To make sum(1) callable as sum(1)(2), it must return a function.
The function can be either called or converted to a number with valueOf.
function sum(a) {
var sum = a;
function f(b) {
sum += b;
return f;
}
f.toString = function() { return sum }
return f
}
function sum(a){
let res = 0;
function getarrSum(arr){
return arr.reduce( (e, sum=0) => { sum += e ; return sum ;} )
}
function calculateSumPerArgument(arguments){
let res = 0;
if(arguments.length >0){
for ( let i = 0 ; i < arguments.length ; i++){
if(Array.isArray(arguments[i])){
res += getarrSum( arguments[i]);
}
else{
res += arguments[i];
}
}
}
return res;
}
res += calculateSumPerArgument(arguments);
return function f(b){
if(b == undefined){
return res;
}
else{
res += calculateSumPerArgument(arguments);
return f;
}
}
}
let add = (a) => {
let sum = a;
funct = function(b) {
sum += b;
return funct;
};
Object.defineProperty(funct, 'valueOf', {
value: function() {
return sum;
}
});
return funct;
};
console.log(+add(1)(2)(3))
After looking over some of the other solutions on here, I would like to provide my two solutions to this problem.
Currying two items using ES6:
const sum = x => y => (y !== undefined ) ? +x + +y : +x
sum(2)(2) // 4
Here we are specifying two parameters, if the second one doesnt exist we just return the first parameter.
For three or more items, it gets a bit trickier; here is my solution. For any additional parameters you can add them in as a third
const sum = x => (y=0) => (...z) => +x + +y + +z.reduce((prev,curr)=>prev+curr,0)
sum(2)()()//2
sum(2)(2)()//4
sum(2)(2)(2)//6
sum(2)(2)(2,2)//8
I hope this helped someone
I'm writing a function that should work like this:
checker(3).equals(3) // true
checker(3).not().equals(3) // false
checker(3).not().equals(4) // true
checker(3).not().not().equals(4) // false
The code I came up with:
function checker(num) {
let number = num
return {
not() {
number = !number
return this
},
equals(nmb) {
return number === nmb
}
}
}
I can't wrap my head around what should not() do so as to make checker(num) work as it is supposed to.
You can add another boolean property that changes how equals works depending on it's value.
function checker(num) {
let number = num
let not = false
return {
not() {
not = !not
return this
},
equals(nmb) {
return not ? number !== nmb : number === nmb
}
}
}
console.log(checker(3).equals(3)) // true
console.log(checker(3).not().equals(3)) // false
console.log(checker(3).not().equals(4)) // true
console.log(checker(3).not().not().equals(4)) // false
Maybe somthing like this:
function checker(num) {
let number = num
let beTrue = true;
return {
not() {
beTrue = !beTrue;
return this
},
equals(nmb) {
return (number === nmb) === beTrue;
}
}
}
It seems to fullfil your requirements. Hope it helps
An ES6 approach
const checker=(number, negate)=>{
const neg = negate || false;
return {
not(){
return checker(number, !neg);
},
equals(number2){
if (neg) return number != number2;
return number == number2;
}
}
}
what should not() do so as to make checker(num) work as it is supposed to.
not could return a new checker.
I think i would let the notfunction control the operator, something like
function checker(num) {
let operator = 'equals';
let number = num
return {
not() {
if(operator==='equals')
operator = 'not equals';
else
operator = 'equals';
return this
},
equals(nmb) {
if(operator==='equals')
return number === nmb
else
return number !== nmb
}
}
}
just using a string as operator for clarity, a proberly better solution could be to use a boolean or number value
I read the article on stack implementation in javascript and python on geeksforgeeks website. I implemented the code to delete the middle element in the stack in javascript exactly as given for python in the same website. But I get wrong answer. Why is it so? what is the difference between the two languages in this case? How can I get the correct answer in javascript? Below is the code in Javascript.
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.items.length === 0) {
return "Underflow";
} else {
return this.items.pop();
}
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length == 0;
}
print() {
console.log(this.items);
}
}
function deleteMid(stack, curr) {
// If stack is empty or all items
// are traversed
if (stack.isEmpty() || curr == stack.items.length) {
return;
}
// Remove last item
x = stack.peek();
stack.pop();
// Remove other items
deleteMid(stack, curr + 1);
console.log("length value: ", stack.items.length);
// Put all items back except middle
if (curr != Math.floor(stack.length / 2)) {
stack.push(x);
}
}
var stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.print();
deleteMid(stack, 0);
stack.print();
There are some parts of the Python implementation that your implementation misses:
You have an implicitly global x variable - unlike Python, in Javascript, variables declared without var / let / const are assigned to the global object, so once the recursive deleteMids have completed, there's only been one variable named x (rather than one for each iteration) which you've reassigned every time. Use const x instead, to ensure that every call of deleteMid has its own binding of x.
Your stack does not have a length property, so your curr != Math.floor(stack.length/2) test results in curr != NaN - which isn't what you want. Although you could give your stack a length getter property:
get length() {
return this.items.length;
}
this still does not conform to the Python implementation, which continually recursively passes the initial length, as another argument: if you want to imitate the Python implementation, do this too, with an n variable:
function deleteMid(stack, n, curr) {
// ...
// Remove other items
deleteMid(stack, n, curr + 1);
// Put all items back except middle
if (curr != Math.floor(n / 2)) {
// ...
// Call with:
deleteMid(stack, stack.items.length, 0);
The problem with checking the length property is that it will change while you're iterating, which will make things much more difficult to work with.
For the same reason, so that even sized stacks work, we also need to change your JS test here:
if (stack.isEmpty() || curr == stack.items.length) {
to correspond to the Python code:
if (st.isEmpty() or curr == n) :
Working code:
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.items.length === 0) {
return "Underflow";
} else {
return this.items.pop();
}
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length == 0;
}
print() {
console.log(this.items);
}
get length() {
return this.items.length;
}
}
function deleteMid(stack, n, curr) {
// If stack is empty or all items
// are traversed
if (stack.isEmpty() || curr === n) {
return;
}
// Remove last item
const x = stack.peek();
stack.pop();
// Remove other items
deleteMid(stack, n, curr + 1);
// Put all items back except middle
if (curr != Math.floor((n) / 2)) {
stack.push(x);
}
}
var stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.print();
deleteMid(stack, stack.items.length, 0);
stack.print();
Since you know the middle index when you start, you can check the stack's length after each item's removal, and stop when you hit the middle.
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.items.length === 0) {
return "Underflow";
} else {
return this.items.pop();
}
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length == 0;
}
print() {
console.log(this.items);
}
}
function deleteMid(stack, middle = Math.round(stack.items.length / 2)) {
if (stack.isEmpty()) return;
const isMiddle = stack.items.length === middle;
// Remove last item
const x = stack.pop();
// stop when you get to the middle
if (isMiddle) return;
// Remove other items
deleteMid(stack, middle);
// add the item back
stack.push(x);
}
var stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.print();
deleteMid(stack);
stack.print();
I want to write a function that checks if the given number has a certain order.
The second number has to be the square of the previous number.
The first number can only be 0 - 9.
So for example 2439 would return 'true' because 4 is the square of 2 and 9 is the square of 3.
39416 would also give 'true', and for example 1624 would return 'false'.
I don't really have an idea how to do this. It should be a recursive function but an example of how to do it without recursion would be helpfull too.
I would try something like this:
function isOrdered(input){
var position = 0;
while(position<input.length-2)
{
var currentFirstNumber = parseInt(input[position]);
if(currentFirstNumber<=2) {
if (Math.sqrt(parseInt(input[position + 1])) !== currentFirstNumber)
return false;
else
position+=2;
}
if(currentFirstNumber>=4 && currentFirstNumber<=9)
{
var squared = input.substring(position+1,position+3);
if(Math.sqrt(parseInt(squared))!==currentFirstNumber)
return false;
else
position=position+3;
}
}
return true;
}
console.log(isOrdered("2439")); // outputs true
console.log(isOrdered("39416")); // outputs true
console.log(isOrdered("1624")); // outputs false
I pass the number to the function as a string.
Take a look at this recursive function
function detectOrder(input)
{
var input = input.toString()
var first = input.substr(0,1);
var power = Math.pow(parseInt(first), 2);
var powerLength = power.toString().length;
if ( parseInt(input.substr(1, powerLength)) == power )
{
if (input.length <= 1+powerLength)
{
return true;
}
else
{
return detectOrder(input.substr(1+powerLength));
}
}
else
{
return false;
}
}
As mention in the comment section, OP said that the 'firsts' are limited to 0..9. So the easiest way to accomplish this is by going through the power function instead of the square root function.
UPDATE: Sorry, you asked for JavaScript code. Be careful with the FIRST CALL. if you manually pass to the function the last position, it will return true.
function verification(number, position){
var str = String(number); // Cast number to String
if(str.length > position){ // Verify valid position
var value = str.substr(position, 1); // take the 'first' value
var pow = Math.pow(value, 2); // Calculate the power
// Verify if the next value is equivalent to the power
if(str.indexOf(pow, position) == position + 1){
// Recursive call to verify the next position
return verification(number, position + String(pow).length + 1);
} else {
// If not equivalent, you found an inconsistency.
return false;
}
// If you ran it until you reached the last position, you're good to go.
}else if(str.length == position){
return true;
}
}
console.log(verification(39416, 0)); // True
console.log(verification(39415, 0)); // True
console.log(verification(981524, 0)); // false
console.log(verification(981525, 0)); // true
console.log(verification(98525, 0)); // false
I want to make this syntax possible:
var a = add(2)(3); //5
based on what I read at http://dmitry.baranovskiy.com/post/31797647
I've got no clue how to make it possible.
You need add to be a function that takes an argument and returns a function that takes an argument that adds the argument to add and itself.
var add = function(x) {
return function(y) { return x + y; };
}
function add(x) {
return function(y) {
return x + y;
};
}
Ah, the beauty of JavaScript
This syntax is pretty neat as well
function add(x) {
return function(y) {
if (typeof y !== 'undefined') {
x = x + y;
return arguments.callee;
} else {
return x;
}
};
}
add(1)(2)(3)(); //6
add(1)(1)(1)(1)(1)(1)(); //6
It's about JS curring and a little strict with valueOf:
function add(n){
var addNext = function(x) {
return add(n + x);
};
addNext.valueOf = function() {
return n;
};
return addNext;
}
console.log(add(1)(2)(3)==6);//true
console.log(add(1)(2)(3)(4)==10);//true
It works like a charm with an unlimited adding chain!!
function add(x){
return function(y){
return x+y
}
}
First-class functions and closures do the job.
function add(n) {
sum = n;
const proxy = new Proxy(function a () {}, {
get (obj, key) {
return () => sum;
},
apply (receiver, ...args) {
sum += args[1][0];
return proxy;
},
});
return proxy
}
Works for everything and doesn't need the final () at the end of the function like some other solutions.
console.log(add(1)(2)(3)(10)); // 16
console.log(add(10)(10)); // 20
try this will help you in two ways add(2)(3) and add(2,3)
1.)
function add(a){ return function (b){return a+b;} }
add(2)(3) // 5
2.)
function add(a,b){
var ddd = function (b){return a+b;};
if(typeof b =='undefined'){
return ddd;
}else{
return ddd(b);
}
}
add(2)(3) // 5
add(2,3) // 5
ES6 syntax makes this nice and simple:
const add = (a, b) => a + b;
console.log(add(2, 5));
// output: 7
const add2 = a => b => a + b;
console.log(add2(2)(5));
// output: 7
Arrow functions undoubtedly make it pretty simple to get the required result:
const Sum = a => b => b ? Sum( a + b ) : a;
console.log(Sum(3)(4)(2)(5)()); //14
console.log(Sum(3)(4)(1)()); //8
This is a generalized solution which will solve add(2,3)(), add(2)(3)() or any combination like add(2,1,3)(1)(1)(2,3)(4)(4,1,1)(). Please note that few security checks are not done and it can be optimized further.
function add() {
var total = 0;
function sum(){
if( arguments.length ){
var arr = Array.prototype.slice.call(arguments).sort();
total = total + arrayAdder(arr);
return sum;
}
else{
return total;
}
}
if(arguments.length) {
var arr1 = Array.prototype.slice.call(arguments).sort();
var mytotal = arrayAdder(arr1);
return sum(mytotal);
}else{
return sum();
}
function arrayAdder(arr){
var x = 0;
for (var i = 0; i < arr.length; i++) {
x = x + arr[i];
};
return x;
}
}
add(2,3)(1)(1)(1,2,3)();
This will handle both
add(2,3) // 5
or
add(2)(3) // 5
This is an ES6 curry example...
const add = (a, b) => (b || b === 0) ? a + b : (b) => a + b;
This is concept of currying in JS.
Solution for your question is:
function add(a) {
return function(b) {
return a + b;
};
}
This can be also achieved using arrow function:
let add = a => b => a + b;
solution for add(1)(2)(5)(4)........(n)(); Using Recursion
function add(a) {
return function(b){
return b ? add(a + b) : a;
}
}
Using ES6 Arrow function Syntax:
let add = a => b => b ? add(a + b) : a;
in addition to what's already said, here's a solution with generic currying (based on http://github.com/sstephenson/prototype/blob/master/src/lang/function.js#L180)
Function.prototype.curry = function() {
if (!arguments.length) return this;
var __method = this, args = [].slice.call(arguments, 0);
return function() {
return __method.apply(this, [].concat(
[].slice.call(args, 0),
[].slice.call(arguments, 0)));
}
}
add = function(x) {
return (function (x, y) { return x + y }).curry(x)
}
console.log(add(2)(3))
Concept of CLOSURES can be used in this case.
The function "add" returns another function. The function being returned can access the variable in the parent scope (in this case variable a).
function add(a){
return function(b){
console.log(a + b);
}
}
add(2)(3);
Here is a link to understand closures http://www.w3schools.com/js/js_function_closures.asp
const add = a => b => b ? add(a+b) : a;
console.log(add(1)(2)(3)());
Or (`${a} ${b}`) for strings.
With ES6 spread ... operator and .reduce function. With that variant you will get chaining syntax but last call () is required here because function is always returned:
function add(...args) {
if (!args.length) return 0;
const result = args.reduce((accumulator, value) => accumulator + value, 0);
const sum = (...innerArgs) => {
if (innerArgs.length === 0) return result;
return add(...args, ...innerArgs);
};
return sum;
}
// it's just for fiddle output
document.getElementById('output').innerHTML = `
<br><br>add() === 0: ${add() === 0 ? 'true' : 'false, res=' + add()}
<br><br>add(1)(2)() === 3: ${add(1)(2)() === 3 ? 'true' : 'false, res=' + add(1)(2)()}
<br><br>add(1,2)() === 3: ${add(1,2)() === 3 ? 'true' : 'false, res=' + add(1,2)()}
<br><br>add(1)(1,1)() === 3: ${add(1)(1,1)() === 3 ? 'true' : 'false, res=' + add(1)(1,1)()}
<br><br>add(2,3)(1)(1)(1,2,3)() === 13: ${add(2,3)(1)(1)(1,2,3)() === 13 ? 'true' : 'false, res=' + add(2,3)(1)(1)(1,2,3)()}
`;
<div id='output'></div>
can try this also:
let sum = a => b => b ? sum(a + b) :a
console.log(sum(10)(20)(1)(32)()) //63
const sum = function (...a) {
const getSum = d => {
return d.reduce((i,j)=> i+j, 0);
};
a = getSum(a);
return function (...b) {
if (b.length) {
return sum(a + getSum(b));
}
return a;
}
};
console.log(sum(1)(2)(3)(4,5)(6)(8)())
function add(a, b){
return a && b ? a+b : function(c){return a+c;}
}
console.log(add(2, 3));
console.log(add(2)(3));
This question has motivated so many answers already that my "two pennies worth" will surely not spoil things.
I was amazed by the multitude of approaches and variations that I tried to put "my favourite" features, i. e. the ones that I would like to find in such a currying function together, using some ES6 notation:
const add=(...n)=>{
const vsum=(a,c)=>a+c;
n=n.reduce(vsum,0);
const fn=(...x)=>add(n+x.reduce(vsum,0));
fn.toString=()=>n;
return fn;
}
let w=add(2,1); // = 3
console.log(w()) // 3
console.log(w); // 3
console.log(w(6)(2,3)(4)); // 18
console.log(w(5,3)); // 11
console.log(add(2)-1); // 1
console.log(add()); // 0
console.log(add(5,7,9)(w)); // 24
.as-console-wrapper {max-height:100% !important; top:0%}
Basically, nothing in this recursively programmed function is new. But it does work with all possible combinations of arguments mentioned in any of the answers above and won't need an "empty arguments list" at the end.
You can use as many arguments in as many currying levels you want and the result will be another function that can be reused for the same purpose. I used a little "trick" to also get a numeric value "at the same time": I redefined the .toString() function of the inner function fn! This method will be called by Javascript whenever the function is used without an arguments list and "some value is expected". Technically it is a "hack" as it will not return a string but a number, but it will work in a way that is in most cases the "desired" way. Give it a spin!
Simple Recursion Solution for following use cases
add(); // 0
add(1)(2)(); //3
add(1)(2)(3)(); //6
function add(v1, sum = 0) {
if (!v1) return sum;
sum += v1
return (v2) => add(v2, sum);
}
function add() {
var sum = 0;
function add() {
for (var i=0; i<arguments.length; i++) {
sum += Number(arguments[i]);
}
return add;
}
add.valueOf = function valueOf(){
return parseInt(sum);
};
return add.apply(null,arguments);
}
// ...
console.log(add() + 0); // 0
console.log(add(1) + 0);/* // 1
console.log(add(1,2) + 0); // 3
function A(a){
return function B(b){
return a+b;
}
}
I found a nice explanation for this type of method. It is known as Syntax of Closures
please refer this link
Syntax of Closures
Simply we can write a function like this
function sum(x){
return function(y){
return function(z){
return x+y+z;
}
}
}
sum(2)(3)(4)//Output->9
Don't be complicated.
var add = (a)=>(b)=> b ? add(a+b) : a;
console.log(add(2)(3)()); // Output:5
it will work in the latest javascript (ES6), this is a recursion function.
Here we use concept of closure where all the functions called inside main function iter refer and udpate x as they have closure over it. no matter how long the loop goes , till last function , have access to x.
function iter(x){
return function innfunc(y){
//if y is not undefined
if(y){
//closure over ancestor's x
x = y+x;
return innfunc;
}
else{
//closure over ancestor's x
return x;
}
}
}
iter(2)(3)(4)() //9
iter(1)(3)(4)(5)() //13
let multi = (a)=>{
return (b)=>{
return (c)=>{
return a*b*c
}
}
}
multi (2)(3)(4) //24
let multi = (a)=> (b)=> (c)=> a*b*c;
multi (2)(3)(4) //24
we can do this work using closure.
function add(param1){
return function add1(param2){
return param2 = param1 + param2;
}
}
console.log(add(2)(3));//5
I came up with nice solution with closure, inner function have access to parent function's parameter access and store in its lexical scope, when ever we execute it, will get answer
const Sum = function (a) {
return function (b) {
return b ? Sum(a + b) : a;
}
};
Sum(1)(2)(3)(4)(5)(6)(7)() // result is 28
Sum(3)(4)(5)() // result is 12
Sum(12)(10)(20) // result is 42
enter image description here
You should go in for currying to call the function in the above format.
Ideally, a function which adds two numbers will be like,
let sum = function(a, b) {
return a + b;
}
The same function can be transformed as,
let sum = function(a) {
return function(b) {
return a+b;
}
}
console.log(sum(2)(3));
Let us understand how this works.
When you invoke sum(2), it returns
function(b) {
return 2 + b;
}
when the returned function is further invoked with 3, b takes the value 3. The result 5 is returned.
More Detailed Explanation:
let sum = function(a) {
return function(b) {
return a + b;
}
}
let func1 = sum(2);
console.log(func1);
let func2 = func1(3)
console.log(func2);
//the same result can be obtained in a single line
let func3 = sum(2)(3);
console.log(func3);
//try comparing the three functions and you will get more clarity.
This is a short solution:
const add = a => b => {
if(!b) return a;
return add(a + b);
}
add(1)(2)(3)() // 6
add(1)(2)(3)(4)(5)() // 15