Getting a RangeError: Invalid count value
at String.repeat (native)
at Object.pad (/home/ccuser/workspace/underscore-javascript-capstone/_.js:31:71)
at Object. (/home/ccuser/workspace/underscore-javascript-capstone/test/pad.js:15:79)
Help is greatly appreciated! Here is the code:
pad(string, length) {
if(length <= string.length) {
return string
}
const startPaddingLength = Math.floor(length - string.length / 2);
const endPaddingLength = length - string.length - startPaddingLength;
const paddedString =’ '.repeat(startPaddingLength) + string + ’ '.repeat(endPaddingLength);
return paddedString
Hey!
I believe I’ve figured out why you’re getting this error, but I don’t have enough information/knowledge to help you achieve the goal of this code.
The RangeError: Invalid count value(chrome browser) is communicating to us that your repeat(argument) is infinite(less than 0).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Resulting_string_too_large
Is this all of the code? My understanding isn’t strong enough to problem-solve effectively without trial and error and a debug/error console. Can you share a gist link with us so we can review and run the code in total?
On line 5, your code is performing as if it’s written Math.floor(length-(string.length / 2))
, executing the nested parenthesis first. Are you sure it’s not supposed to be Math.floor((length - string.length) / 2)
, executing the subtraction first?
Let’s walk through the code assuming I called pad('butts', 6);
Because the length(*6*)
is greater than the string.length(*5*)
, we don’t meet the set if
condition. The method/function skips the if block.
Line 5 returns Math.floor(length(*6*) - string.length(*5*) / 2) = 3
Line 6 returns length(*6*) - string.length(*5*) - startPaddingLength(*3*) = -2' Line 7 passes the
endPaddingLength(-2)` variable as a repeat argument, but it’s a negative integer which repeat does not accept.
I can’t fully understand the total goal of this code at my current level of understanding, but I believe your negative integer produced on line 6 is creating RangeErrors on the .repeat() used on line 7.
I hope this helps you understand the error better. I’m sorry I can’t be of more help here.
Good luck!
P.S. I believe line 7 may also have some conflicts between the template literals and single quotes. I would revisit this line in the code to make sure it’s functioning the way you want it to.
Yay! That worked! Thank you so much for your help, I really appreciate it!!
Although I am completing all the exercises with Codecademy, I often require many hints, and often even skip towards the answer, I was wondering if you had any advice on how I could better my learning?