Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How could this be done better or more elegant ? Below is my solution and according to the evaluation of the exercise it works and i passed but i feel like code is too crude.

Here is the exercise:

_________________________________________

Write a function cutComment that takes one line of JavaScript and returns a possible line comment trimmed. If the line contains no line comment, null should be returned. For simplicity, we assume that the code does not contain the comment characters within a string.

Example: cutCommt('let foo; // bar') should return 'bar'.

_________________________________________

so you see my code works but i feel like there is maybe better solution. thanks.

What I have tried:

const cutComment = string => {

let onlyComment = string.indexOf('//');

if (string.indexOf('/') < 1) {

return null;

}

return string.substr(onlyComment+2).trim();

}
Posted
Updated 31-May-22 22:37pm

Why is your if condition like that? If the code was this:
let x = 28 / 7;
Would it return the right value?
Shouldn't the if involve the result from the previous line?
 
Share this answer
 
function cutComment(string) {

let onlyComment = string.indexOf('//');

if ( onlyComment < 1) {

return null;

}else
{

return string.substr((onlyComment+3),string.length);
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900