Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. function isNumber(l) {
  2. return /^[0-9]$/.test(l)
  3. }
  4.  
  5. function isSpace(l) {
  6. return l === ' '
  7. }
  8.  
  9. function isDot(l) {
  10. return l === '.'
  11. }
  12.  
  13. function isValidLetter(l){
  14. return isNumber(l) || isSpace(l) || isDot(l)
  15. }
  16.  
  17. function ipv4ToInt(input) {
  18. const ip = '.'+input
  19. const length = ip.length
  20. let order = 0
  21. let result = 0
  22. let current = ""
  23. let spaceAfterNumberOccur = false
  24. for (let i = 0; i < length; i++){
  25. const position = length-i-1
  26. const letter = ip[position]
  27. if (!isValidLetter(letter)) throw new Error(`read invalid letter ${letter} at ${position}`)
  28.  
  29. if (isNumber(letter) && spaceAfterNumberOccur) throw new Error(`space between number at ${position}`)
  30.  
  31. if (isNumber(letter)) {
  32. current = letter + current
  33. } else if (isSpace(letter)){
  34. if (isNumber(current[0])) spaceAfterNumberOccur = true
  35. } else if (isDot(letter)){
  36. result += parseInt(current, 10) * Math.pow(256, order)
  37. order += 1
  38. current = ""
  39. spaceAfterNumberOccur = false
  40. } else {
  41. throw new Error(`invalid input, this should not occur unless you removed the guard code.`)
  42. }
  43. }
  44. return result
  45. }
  46.  
  47. function assert(i, j) {
  48. if (i !== j) throw new Error(`${i} not equal to ${j}`)
  49. }
  50.  
  51. function shouldThrow(fn) {
  52. try{
  53. fn()
  54. } catch(e){
  55. return
  56. }
  57. throw new Error('should throw error, but it did not.')
  58. }
  59.  
  60. function test() {
  61. assert(ipv4ToInt("172.168.5.1"), 2896692481)
  62. assert(ipv4ToInt("172 .168.5.1"), 2896692481)
  63. assert(ipv4ToInt("172. 168.5.1"), 2896692481)
  64. assert(ipv4ToInt(" 172.168.5.1"), 2896692481)
  65. shouldThrow(function() { ipv4ToInt("172.16 8.5.1") })
  66. shouldThrow(function() { ipv4ToInt("172.168.a.1") })
  67. console.log('all pass')
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement