Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 (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.`)
- }
- }
- 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") })
- console.log('all pass')
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement