Some Fun with Javascript

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,396
Reaction score
1,186
I know there are some bright engineers here. Here I have a question for anyone interested to just give it a try, just for fun.

Are you able to design a Javascript 'add' function that take in at least one argument, and up to in theory "infinite" number of arguments (limited by the amount of memory available) and capable of evaluating test codes below.

You can code using any particular standard of Javascript, I would say stick with ECMA2015 since it is the popular one right now supported by most modern browsers. You are free to code any number of helper functions as long as there is an 'add' function that can execute the test codes below, and will produce the EXACT output as accordingly.

There is no need to consider on performance, good or bad intent of the exercise, good or bad practices, or whatsoever reason. Basically all it matters is if you can design such a function that will work as accordingly.

It should pass the following set of testing codes and produce the following outputs below.

Testing Codes:
Code:
console.log(add(-1));
console.log(add(0));
console.log(add(1));
console.log(add(1)(2));
console.log(add(1)(2)(3));
console.log(1000 + add(1)(2)(3));
console.log(add(1)(2)(3) - 1000);
console.log(add(1)(2)(3) * 10);
console.log(10 * add(1)(2)(3));
var s = "add(" + [...Array(1000).keys()].join(")(") + ")";
eval("console.log(" + s + ")");

Expected Output:
Code:
-1
0
1
3
6
1006
-994
60
60
499500

For the sake of other interested parties to try, do POST your codes inside SPOILER tags so that they can try without looking at your solution, unless they wanted to.

Feel free to give it a try!
I will upload my solution, after lets say a week or more depending on activeness of this thread.
Happy coding. :)

UPDATE: 11-Aug-2019

Seems like there wouldn't be much activity, hence my solution is provided below. I will put in the SPOILER so that if anyone notice this thread and want to give it a go, feel free to do so.
Before you go further, have you try it out of your own ? If you have not, my hints are as follows
[1] Usage of Closures
[2] Understanding First Class Functions in functional languages and its approach
[3] Understanding Curry and Function Composition, also part of functional programming techniques

Generally,

F(X)(Y)(Z) is effectively ((F(X))(Y))(Z). It is a function that returns a function, which is why it seems like there is a stacking of parentheses.

With the above hints, you can study on them and see if you can solve the problem. If you insist that you want to see the solution, go ahead :)
Code:
const add = x => {
  var s = 0;
  var q = x => { s += x; return q; }
  q.toString = () => s;
  return q(x);
}

Someone else in this thread has provided a similar variant solution to mine, which is right too, you can also consider that particular way of solving this solution. :)
 
Last edited:

TrueBeliever_jh

Honorary Member
Joined
Jun 8, 2006
Messages
112,795
Reaction score
4,436
after Googling
Code:
const add = x => {
  var sum = x;

  const f = y => {
    sum += y;
    return f;
  };
  f.toString = () => sum;
  f.valueOf = () => sum;

  return f;
};

interesting. console.log doesn't seem to evaluate `function.toString`

will spend some time this afternoon again if i can think of a solution..
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,396
Reaction score
1,186
after Googling

interesting. console.log doesn't seem to evaluate `function.toString`

will spend some time this afternoon again if i can think of a solution..

So have you wonder or know why it works? Would you be able to solve without googling? What are the key techniques to make the solution works :)
 
Last edited:

TrueBeliever_jh

Honorary Member
Joined
Jun 8, 2006
Messages
112,795
Reaction score
4,436
So have you wonder or know why it works? Would you be able to solve without googling? What are the key techniques to make the solution works :)
i always wonder how to do currying with unspecific number of function calls.

good that your question came about. i understand recursive and currying.

too bad overriding `valueOf` never came to my mind until i googled for it. guess i am still not that good with Javascript.

would love to see your solution. next week i guess~?
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,396
Reaction score
1,186
i always wonder how to do currying with unspecific number of function calls.

good that your question came about. i understand recursive and currying.

too bad overriding `valueOf` never came to my mind until i googled for it. guess i am still not that good with Javascript.

would love to see how you gonna solve the `toString` not being evaluated

If you just googled for the valueOf function, you have what it takes to answer this question. It does take a significant leap of skill to understand some of the ideas used in your solution not just Javascript, but general idea of currying, first class citizen of functions and closures. So you are fine :)

That is good you have an idea on currying, a concept from functional programming. Just for note, there is no recursion used in the solution you have provided :) I didn’t use any valueOf function overriding when I was solving it. It is very similar to what you have provided though. However using the valueOf function is a good call too, no issue with that as part of the solution, as long as you know how it is used.
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,396
Reaction score
1,186
Solution is provided in the first post, feel free to examine it and understand it. Have fun coding. :)
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,396
Reaction score
1,186
The former is achieved easily via args
The latter is kinda like currying but recursively

Did you mix up between former and latter? No recursion required, suppose we fix to the correct terminology of recursion :)
 

cwchong

Master Member
Joined
Jan 7, 2005
Messages
4,635
Reaction score
77
Some self notes in case i forgot:
The shape of the function should prob be like returning either a value, or a function
Not quite sure how that would be achieved yet, without an end condition like recursion, just keeping inmind

Maybe shaped like
add = (n) => {
return (m) => {
return m+n;
};
}

But of cos this only works for 2 args so needs something else magical
 
Last edited:

cwchong

Master Member
Joined
Jan 7, 2005
Messages
4,635
Reaction score
77
Did you mix up between former and latter? No recursion required, suppose we fix to the correct terminology of recursion :)

Didnt mix up, just typed wrongly ha
Not recusion in the type of function sense, just lack of better descriptor
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,396
Reaction score
1,186
Some self notes in case i forgot:
The shape of the function should prob be like returning either a value, or a function
Not quite sure how that would be achieved yet, without an end condition like recursion, just keeping inmind

No problem. I have written some hints when you unwrap the first spoiler in the first post. If you like, feel free to take a look. If you want to figure it out yourself, that is better :)
 

peterchan75

Supremacy Member
Joined
Apr 26, 2003
Messages
6,494
Reaction score
457
No problem. I have written some hints when you unwrap the first spoiler in the first post. If you like, feel free to take a look. If you want to figure it out yourself, that is better :)

Does creative or cryptic code make maintenance job difficult ?
Like this anti-patterns by Youtuber Techlead.
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,396
Reaction score
1,186
Does creative or cryptic code make maintenance job difficult ?
Like this anti-patterns by Youtuber Techlead.
...

No doubt it will. But I guess one will be trying too hard to just do all these so that one can stay in a company. It's a prison for both parties if you really think about it. If your future employer do a reference with your old company, do you think it will be advantages for you ? Well I think not much thoughts required.

Creative or cryptic codes is a fine line apart. Personally I can write very cryptic perl codes despite I don't do it for my own benefit, not so much of others. I don't like to spend too much time on history and would like to focus on advancement. But if I need to exploit certain features in a programming language and some parts of the system will be cryptic, I will compensate by adequate comments and documentation that describe about the complex technique. I have codes with comments taking much more lines than the codes. This is the same advice I give to my peers when I'm code reviewing them too.

If you are working among fine developers, those set of complex codes might actually be considered EASY for them. So how are you going to draw the line between EASY and CRYPTIC(HARD/COMPLEX). Thus I guess you need to know your environment and who are the audience to those modules. Simple codes sometimes don't exploit the features and underlying platform sufficiently to bring in the performance required.
 
Last edited:
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ. Forum members and moderators are responsible for their own posts.

Please refer to our Community Guidelines and Standards, Terms of Service and Member T&Cs for more information.
Top