Created
June 18, 2024 17:55
-
-
Save theArina/6ad5d2c812cdbf4bee5f0ef87a56acd0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function myParseInt(input) { | |
let result = 0; | |
let isNegative = false; | |
let i = 0; | |
input = input.trim(); | |
if (input[0] === '-') { | |
isNegative = true; | |
i = 1; | |
} else if (input[0] === '+') { | |
i = 1; | |
} | |
if (/\D/.test(input[i])) { | |
return NaN; | |
} | |
const ZERO_ASCII_CODE = '0'.charCodeAt(0); | |
for (; i < input.length; i++) { | |
const char = input[i]; | |
if (/\D/.test(char)) { | |
break; | |
} | |
result = result * 10 + (char.charCodeAt(0) - ZERO_ASCII_CODE); | |
} | |
if (isNegative) { | |
result = -result; | |
} | |
return result; | |
} | |
const testInputs = [ | |
'123', | |
' 456 ', | |
'-789', | |
'+1011', | |
' -2222 ', | |
'42abc', | |
'abc42', | |
'', | |
' ', | |
'+', | |
'-', | |
'0', | |
'-0', | |
]; | |
testInputs.forEach((input, index) => { | |
const myResult = myParseInt(input); | |
const nativeResult = parseInt(input); | |
console.log(`----- Test ${index + 1} -----`); | |
console.log(` Input: "${input}"`); | |
console.log('Native parseInt result:', nativeResult); | |
console.log(' My parseInt result:', myResult); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment