_.pad ()

I am working on a course project and I am making a method called pad () in a _ object. Here is the code for the method:

[codebyte]

[/English]
pad (str, length) {
if (typeof str !== “string”) {
return “Invalid input”;
}
let difference = length - str.length;
if (difference %2 === 0) {
let halfDifference = difference / 2;
let length1 = halfDifference + str.length;
let pad1 = str.padStart(length1, ’ ');
let length2 = halfDifference + pad1.length;
return str.padEnd(length2, ’ ');
} else {
let newDifference1 = ((difference - 1) / 2);
let length1 = newDifference1 + str.length;
let pad1 = str.padStart(length1, ’ ');
let newDifference2 = ((difference - 1) / 2) + 1;
let length2 = newDifference2 + pad1.length;
return str.padEnd(length2, ’ ');
}
}

This is the test code:

[codebyte]

[/English]
const _ = require(’…/_.js’);
const assert = require(’./assert.js’);

const TEST_NAME = ‘_.pad()’;

assert.beginTestBlock(TEST_NAME);

assert.exists(TEST_NAME, ‘_.pad()’, _.pad);

if (!_.pad) {
assert.terminateTestBlock();
return;
}

assert.equals(TEST_NAME, ‘Returns evenly-padded strings’, ‘_.pad(“hi”, 6)’, .pad(“hi”, 6), " hi ");
assert.equals(TEST_NAME, ‘Returns oddly-padded strings with extra padding on right side’, '
.pad(“hi”, 5)’, .pad(“hi”, 5), " hi ");
assert.equals(TEST_NAME, ‘Returns strings longer than provided length un-padded’, '
.pad(“hello”, 4)’, _.pad(“hello”, 4), “hello”);

assert.endTestBlock();

For some reason, when I test the first code for my method, I get this type error:

let pad1 = str.padStart(length1, ’ ');
^
TypeError: str.padStart is not a function

I do not understand why this type error is occurring. I am clearly referencing the string, str to be used for the method. Str should be an argument for a string, so why is there a type error being made when I use a string on the padStart method. If you look at the test file, you can see 3 arguments being put for the method I am making:
.pad(“hi”, 6);
'
.pad(“hi”, 5);
_.pad(“hello”, 4);

So clearly str is referencing a string. Can somebody explain why this type error is coming and what I can do to fix it?

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.