DEV Community

Discussion on: Basic Algorithm Scripting in JavaScript

Collapse
 
toddster79 profile image
Todd Carlson

Thanks for sharing your solutions! I love seeing what other people come up with because it makes me a better programmer. My code passed the tests on FCC, and I ran it myself with both zero and a negative number. In both instances I got back an empty string.

Collapse
 
pentacular profile image
pentacular

That's because it never gets to the if (Math.sign(num)) bit in your example.

   for (let i = 0; i < num; i++) {
     ...
   }

Initially i === 0, so the guard is initially 0 < num, which will be false if num <= 0.

But you can easily test the behavior of Math.sign.

if (Math.sign(-1)) {
  console.log('Math.sign(-1) is true');
}
if (Math.sign(1)) {
  console.log('Math.sign(1) is true');
}
// Output:
// Math.sign(-1) is true.
// Math.sign(1) is true.
Thread Thread
 
toddster79 profile image
Todd Carlson

"Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number."
dev-to-uploads.s3.amazonaws.com/i/...
dev-to-uploads.s3.amazonaws.com/i/...
dev-to-uploads.s3.amazonaws.com/i/...

Thread Thread
 
pentacular profile image
pentacular

In what case do you think you call Math.sign with a value less than one?

Thread Thread
 
toddster79 profile image
Todd Carlson

I'm using Math.sign() to check whether or not the number is positive or negative. If it never gets to my if statement, then how is it updating the variable and returning the string the correct number of times?

Thread Thread
 
toddster79 profile image
Todd Carlson

I guess I only call Math.sign for the positive case, the else statement returns the empty string for the other cases. I still don't see how this isn't a correct solution to the problem. I check to see if it is a positive number with Math.sign, if it is the variable gets updated and returned the correct number of times. In all other cases, negative or zero, it returns an empty string.

Thread Thread
 
pentacular profile image
pentacular

So, if (Math.sign(num)) { . . . } could be replaced with if (true) { ... } in your code without changing any answer?