Wednesday, May 26, 2021

Javascript Practice 63: JS Hero - null

 
Question: 

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'.




Answer: 

function cutComment (line) {

let a = line.indexOf('//'); 

if (a === -1) { 

return null; 

} else {

return line.slice(a+2).trim(); 

}}; 




> we declare a function cutComment
> it has one parameter 'line'
> we need to check if the function cutComment is called with a string that has a comment line 
> if it has a comment line then we need to remove it 
> and return all the elements of the string after the comment line characters ' // ' 
>>>> so our solution will begin with declaring a variable ' a ' 
>> it will be initialized with a value returned from the indexOf method on the parameter 'line'
>> we basically check for the line comment characters ' // ' in our parameter 'line' 
>> we then store it in the variable ' a ' 
>> we can expect that by using the indexOf method we can get two results
>> first, if there is a comment line character, then we shall be returned with a number
>> second, if there is an absence of comment line character, then we shall be returned with -1
>> we then open an if / else statement 
>> our first condition is to check if there is an absence of value in the variable 'a'
>> like this: a === -1
>> if a === -1, is true then, we return null
>> else we return the line with the elements; 
>> sliced from the beginning of the 'second line comment' character 
>> & trimming all the spaces between the line comment character and the elements after it
>> like this: line.slice(a+2).trim()
>> (a + 2) is used as there are 2 forward slashes that denote a line comment ' // '
>> when we get the indexOf value of the line comment; 
>> it includes only the index of the first forward slash
>> in order to slice the line from the second forward slash we have to add 2 to the variable 'a'
>> this will ensure that the slicing method will start from the end of the 2nd forward slash  
>> we then add the trim method after the slicing has been done
>> the trim method will remove the whitespaces from both the ends of the string that is sliced

No comments:

Post a Comment