SHARE
TWEET

Untitled

a guest Jul 18th, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function parseUrl(urlStr) {
  2.     const [scheme, addressWithQuery] = extractScheme(urlStr)
  3.     const [queryParameters, address] = extractQuery(addressWithQuery)
  4.     const [authority, segments]      = extractSegments(address)
  5.     return [scheme, authority, segments, queryParameters]
  6. }
  7.  
  8. function extractScheme(urlStr) {
  9.     let parts = urlStr.split("://")
  10.     if (parts.length != 2)
  11.         throw "URL is invalid"
  12.     validateScheme(parts[0])
  13.     return parts
  14. }
  15.  
  16. function validateScheme(scheme) {
  17.     if (validSchemes.includes(scheme))
  18.         return
  19.     else
  20.         throw `${scheme} is not a valid URL scheme`
  21. }
  22.  
  23. function extractQuery(addressWithQuery) {
  24.     let parts = urlStr.split("?")
  25.     switch (parts.length) {
  26.         case 1:  return [{}, parts[0]]
  27.         case 2:  return [extractQueryParameters(parts[1]), parts[0]]
  28.         default: throw "URL is invalid"
  29.     }
  30. }
  31.  
  32. function extractQueryParameters(parametersStr) {
  33.     let parametersStr = parametersStr.split("&")
  34.     let parameters = {}
  35.     for (parameterStr of parametersStr) {
  36.         const [key, value] = parseQueryParameter(parameterStr)
  37.         parameters[key] = value
  38.     }
  39.     return parameters
  40. }
  41.  
  42. function parseQueryParameter(parameterStr) {
  43.     let keyValue = parameterStr.split("=")
  44.     switch (keyValue.length) {
  45.         case 1:  return [keyValue[0], null]
  46.         case 2:  return keyValue
  47.         default: throw "URL is invalid"
  48.     }
  49. }
  50.  
  51. function extractSegments(address) {
  52.     let [authority, ...segments] = address.split("/")
  53.     validateAuthority(authority)
  54.     for (segment of segments)
  55.         validateSegment(segment)
  56.     return [authority, segments]
  57. }
  58.  
  59. function validateAuthority(authority) {
  60.     // put authority validation here
  61.     return
  62. }
  63.  
  64. function validateSegment(segment) {
  65.     // put segment validation here
  66.     return
  67. }
  68.  
  69. const validSchemes = ["http", "https", "ftp", "sftp"] // etc.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top