I think I am close but I would to get your feedback to solve this using a derivative of the code I have already created, I pass the following tests, but I am struggling to pass the final test as I need to return two middle names abbreviated, and at the moment I can only return the first. The tests below show the function and parameters passed, and the expected result its the last ione I am struggling with. I would appreciate your expert advice. Kind regards, Jon
Test.assertEquals(initializeNames('Jack Ryan'), 'Jack Ryan', '');
Test.assertEquals(initializeNames('Lois Mary Lane'), 'Lois M. Lane', '');
Test.assertEquals(initializeNames('Dimitri'), 'Dimitri', '');
Test.assertEquals(initializeNames('Alice Betty Catherine Davis'), 'Alice B. C. Davis', '')
function initializeNames(name) {
let seperateNames = name.split(' ');
let output = "";
if (name.length = 2) {
output = name;
}
for (let i = 1; i < seperateNames.length - 1; i++) {
output = seperateNames[i];
let abvName = output.substring(0, 1) + '.';
output = seperateNames[0] + ' ' + abvName + ' ' + seperateNames.slice(-1);
}
return output;
}
This if condition is useless. Because = is assignment and == is equality check.
if (name.length = 2) {
output = name;
}
Also I believe you wanted to check the length of seperateNames array. You already know what to do if length is less than equal to 2.
But if it is not then you need your loop and extra calculation.
Have a look at below code which starts with
the first name, and
add the abvName, and then
the last name
console.log(initializeNames('Jack Ryan'));
console.log(initializeNames('Lois Mary Lane'));
console.log(initializeNames('Dimitri'));
console.log(initializeNames('Alice Betty Catherine Davis'));
function initializeNames(name) {
let seperateNames = name.split(' ');
let output = "";
if (seperateNames.length <= 2) {
output = name;
}
else{ output = seperateNames[0];
for (let i = 1; i < seperateNames.length - 1; i++) {
let currentOutput = seperateNames[i];
let abvName = currentOutput.substring(0, 1) + '.';
output = output + ' ' + abvName + ' ';
}
output += seperateNames[seperateNames.length - 1];
}
return output;
}
Note : x += b; is the same as x = x + b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With