r/javaScriptStudyGroup • u/ForScale • May 10 '16
CHALLENGE: Write a multiplication function...
CHALLENGE:
Write a multiplication function that takes two numbers integers as arguments and returns their product.
Rules:
Cannot use
*or/operatorsCannot use Math object
Cannot use for (any variation) or while (including do) loops
2
u/Volv May 10 '16 edited May 10 '16
Recursion Example. Fixed signs this time Codepen
Although I used a multiply symbol for those signs... hmm
And now I got rid of it
2
u/ForScale May 10 '16
Nice!
Your syntax is getting interesting... Is it common practice to ditch the curly braces with if statements? Or is that a babel thing?
1
u/Volv May 10 '16
Ternary is fairly common for simple if then else when all you are doing is assigning values. That one is nested but I think formatted in such a way that it is obvious enough without being too hard to read?
var resultSign = (x < 0) ? // x less than zero (y > 0) ? -1 : 1 : // x greater than zero (y < 0) ? -1 : 1;
versusvar resultSign = 0; if (x < 0) { if (y > 0) { resultSign = -1; } else { resultSign = 1; } } else { if (y < 0) { resultSign = -1; } else { resultSign = 1; } }1
u/ForScale May 10 '16
:) I'm not that bad! I know ternary, but I don't use it much and I don't think I've ever used it nested like that. Pretty cool!
No, I was talking about current line 29 and 30.
2
u/Volv May 10 '16
Generally advice is to not ditch them. I make exceptions for things like a quick check to break or return..
and in my defence I ditched wayyy more brackets with the ternarys :) Take it you found that ok enough to read. I worry when i start nesting them1
1
u/ForScale May 10 '16
2
u/Volv May 10 '16 edited May 10 '16
Nice. straight for the recursion. I see what you mean about lack of array.fill :) It is another new ES6 thing and according to this doesn't work natively in IE atm. yay babel.
We have pretty similar answers for both it seems. Main difference in second one is you carrying the result (and iteration info) in a closure over main function instead of threaded through the function calls.
Success tho - Only issue is your first solution will fail for negative values of a.. but having said that mine fails for negative y :)2
u/ForScale May 10 '16
Whoops! Didn't consider how a negative a would affect the reduce functionality. I think I fixed it though!
2
2
u/Volv May 10 '16 edited May 10 '16
Not gonna look at yours for a bit cause there must be more ways to do this.
Do you consider this cheating? :)