Skip to content

Instantly share code, notes, and snippets.

@mgax
Last active November 20, 2016 15:02
Show Gist options
  • Save mgax/035e824a855150e8fe4e0c5db01af2cc to your computer and use it in GitHub Desktop.
Save mgax/035e824a855150e8fe4e0c5db01af2cc to your computer and use it in GitHub Desktop.
let url = require('url')
function resolve(baseUrl, extraUrl) {
function urlParse(url) {
let m = url.match(/^(http[s]?:\/\/[^/]+)?(.*)?$/)
if(! m) throw new Error(`Can't parse "${url}"`)
let host = m[1] || ''
let path = m[2] || ''
if(host && ! path) path = '/'
return {host, path}
}
let base = urlParse(baseUrl)
let extra = urlParse(extraUrl)
if(extra.path.slice(0, 2) == './') extra.path = extra.path.slice(2)
if(extra.path) {
let m = base.path.match(/^(.*\/)[^/]*$/)
base.path = m ? m[1] : ''
if(extra.path[0] == '/') base.path = ''
if(base.path.slice(0, 2) == './') base.path = base.path.slice(2)
}
let host = extra.host || base.host
let path = base.path + extra.path
return host + path
}
function testsuite() {
const TESTS = [
'',
'a.txt',
'/a.txt',
'./a.txt',
'/a/b/c.txt',
'http://grep.ro',
'http://grep.ro/x',
'http://grep.ro/x/',
'http://grep.ro/x/y/',
]
for(let base of TESTS) {
for(let extra of TESTS) {
let result = resolve(base, extra)
let expected = url.resolve(base, extra)
console.log(`"${base}", "${extra}", "${result}"`)
if(result != expected) {
console.error('error!', [result, expected])
return
}
}
}
console.log('all ok')
}
testsuite()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment