JavaScript: Safe Integer Parsing
Many applications require converting string representations of numbers into actual integer values. This is a fundamental operation, but it's crucial to handle cases where the input string might not be a valid number, to prevent unexpected behavior or errors. Your task is to create a robust function that safely parses integer strings in JavaScript.
Problem Description
You need to implement a JavaScript function called safeParseInt that takes a single argument: str. This function should attempt to convert the input str into an integer. The key requirement is that the function must gracefully handle non-numeric input and return a specific value (e.g., NaN or null) in such cases.
Key Requirements:
- The function must accept a string as input.
- If the string represents a valid integer (positive, negative, or zero), the function should return its integer equivalent.
- If the string does not represent a valid integer, or if the input is not a string, the function should return
NaN(Not a Number). - The function should handle leading and trailing whitespace correctly.
- The function should ignore any characters that appear after a valid integer representation. For example,
"123abc"should parse as123.
Expected Behavior:
safeParseInt("123")should return123.safeParseInt("-45")should return-45.safeParseInt(" 789 ")should return789.safeParseInt("100px")should return100.safeParseInt("abc")should returnNaN.safeParseInt("")should returnNaN.safeParseInt(null)should returnNaN.safeParseInt(undefined)should returnNaN.safeParseInt(123)(number input) should returnNaNas the input is expected to be a string.
Examples
Example 1:
Input: "42"
Output: 42
Explanation: The input string "42" is a valid integer representation.
Example 2:
Input: " -99bottles "
Output: -99
Explanation: The function correctly parses the integer part "-99" and ignores the trailing non-numeric characters and whitespace.
Example 3:
Input: "hello123world"
Output: NaN
Explanation: The string does not start with a valid integer. Although "123" appears, the parsing begins from the start of the string.
Example 4:
Input: ""
Output: NaN
Explanation: An empty string cannot be parsed as an integer.
Example 5:
Input: 100 (as a number)
Output: NaN
Explanation: The function expects a string input, not a number.
Constraints
- The input will be of any JavaScript type, but the function should only attempt to parse strings.
- The output must be an integer or
NaN. - Performance is not a primary concern for this challenge, but a reasonably efficient solution is preferred.
Notes
Consider using built-in JavaScript functions that might help with this task, but ensure your implementation meets all the specified requirements, especially regarding error handling and edge cases. Remember to think about how JavaScript's native parsing functions behave and whether they directly fulfill all the requirements.