Question:
Write a function parseFirstInt that takes a string and returns the first integer present in the string. If the string does not contain an integer, you should get NaN.
Example: parseFirstInt('No. 10') should return 10 and parseFirstInt('Babylon') should return NaN.
Answer:
function parseFirstInt (input) {
let inputToParse = input;
for (let i = 0; i < input.length; i++) {
let firstInt = parseInt(inputToParse);
if (!Number.isNaN(firstInt)) {
return firstInt;
}
inputToParse = inputToParse.substr(1);
}
return NaN;
};
> we declare a function 'parseFirstInt'
> it has 1 parameter 'input'
> we declare a variable 'inputToParse'
> we initialize it with a value of the input string
> we use a 'for loop' to loop over the elements of the input string
> we then declare another variable inside the 'for loop' which is 'firstInt'
> we initialize its value with the output we get when we run the parseInt method on variable 'inputToParse' and store them in the firstInt variable
> for eg lets say our 'inputToParse' is 'Javascript 101'
> so parseInt will give us a NaN output
> this will be stored in firstInt variable
> we then open an ' if ' statement to check if firstInt is ' NaN ' or ' not NaN '
> if it is NaN then the code inside the block of ' if ' statement does not run
> instead we apply the substr(1) method which returns a portion of the string from the index 1 and extending up to the last index.
> so the new 'inputToParse' value shall be ' avascript 101'
> this value will get stored in the 'firstInt' variable and again the condition in the ' if ' statement will be checked
> this process will keep on repeating itself till the loop stopping condition is met
> if we encounter any numbers then they get stored in the 'firstInt' variable
> if there are no occurrences of numbers then we will have nothing stored in the variable 'firstInt'
> the stopping condition is met once we run out of characters in 'inputToParse' variable
> so if we do have numbers then the function will return the integer
> if the stopping condition is met and we do not find any integers then we shall be returned NaN
No comments:
Post a Comment