Skip to content

Instantly share code, notes, and snippets.

@sskyy
Last active July 24, 2017 09:13
Show Gist options
  • Save sskyy/53583d6df28e58e314c2305b5f38e77d to your computer and use it in GitHub Desktop.
Save sskyy/53583d6df28e58e314c2305b5f38e77d to your computer and use it in GitHub Desktop.
function isNumber(l) {
return /^[0-9]$/.test(l)
}
function isSpace(l) {
return l === ' '
}
function isDot(l) {
return l === '.'
}
function isValidLetter(l){
return isNumber(l) || isSpace(l) || isDot(l)
}
function ipv4ToInt(input) {
const ip = '.'+input
const length = ip.length
let order = 0
let result = 0
let current = ""
let spaceAfterNumberOccur = false
for (let i = 0; i < length; i++){
const position = length-i-1
const letter = ip[position]
if (!isValidLetter(letter)) throw new Error(`read invalid letter ${letter} at ${position}`)
if (isDot(letter) && current === '') throw new Error(`no address read at ${position}`)
if (isNumber(letter) && spaceAfterNumberOccur) throw new Error(`space between number at ${position}`)
if (isNumber(letter)) {
current = letter + current
} else if (isSpace(letter)){
if (isNumber(current[0])) spaceAfterNumberOccur = true
} else if (isDot(letter)){
result += parseInt(current, 10) * Math.pow(256, order)
order += 1
current = ""
spaceAfterNumberOccur = false
} else {
throw new Error(`invalid input, this should not occur unless you removed the guard code.`)
}
}
if(order !== 4) throw new Error(`input is not complete`)
return result
}
function assert(i, j) {
if (i !== j) throw new Error(`${i} not equal to ${j}`)
}
function shouldThrow(fn) {
try{
fn()
} catch(e){
return
}
throw new Error('should throw error, but it did not.')
}
function test() {
assert(ipv4ToInt("172.168.5.1"), 2896692481)
assert(ipv4ToInt("172 .168.5.1"), 2896692481)
assert(ipv4ToInt("172. 168.5.1"), 2896692481)
assert(ipv4ToInt(" 172.168.5.1"), 2896692481)
shouldThrow(function() { ipv4ToInt("172.16 8.5.1") })
shouldThrow(function() { ipv4ToInt("172.168.a.1") })
shouldThrow(function() { ipv4ToInt("168.1.1") })
shouldThrow(function() { ipv4ToInt("172.168..1") })
console.log('all pass')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment