Last active
February 23, 2018 09:40
-
-
Save WebMaestroFr/567c90000744d5df4db32779c4af2155 to your computer and use it in GitHub Desktop.
URL Parser and Media Promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function encodeURLParams(params) { | |
return Object | |
.entries(params) | |
.sort((a, b) => a[0] - b[0]) | |
.reduce((search, entry) => [ | |
...search, | |
entry | |
.map(encodeURIComponent) | |
.join('=') | |
], []) | |
.join('&'); | |
} | |
export function composeURL(base, params) { | |
return params | |
? `${base}?${encodeURLParams(params)}` | |
: base; | |
} | |
export function parseURLSearch(search) { | |
return search | |
.substring(1) | |
.split('&') | |
.reduce((params, param) => { | |
const entry = param | |
.split('=') | |
.map(decodeURIComponent); | |
return { | |
...params, | |
[entry[0]]: entry[1] | |
}; | |
}, {}); | |
} | |
export default function parseURL(url) { | |
const parser = document.createElement('a'); | |
parser.href = url; | |
const { | |
hash, | |
host, | |
hostname, | |
href, | |
origin, | |
pathname, | |
port, | |
protocol, | |
search | |
} = parser; | |
return { | |
hash, | |
host, | |
hostname, | |
href, | |
origin, | |
pathname, | |
port, | |
protocol, | |
search, | |
path: origin + pathname, | |
params: parseURLSearch(search), | |
getImg: (t = 0) => new Promise((resolve, reject) => { | |
const image = document.createElement('img'), | |
timeout = t && setTimeout(() => { | |
image.src = "//!!!/timeout"; | |
reject("Image timed out."); | |
}, t); | |
image.onload = e => { | |
timeout && clearTimeout(timeout); | |
resolve(e.target); | |
}; | |
image.onerror = e => { | |
timeout && clearTimeout(timeout); | |
reject(e); | |
}; | |
image.src = href; | |
}), | |
getVideo: (t = 0) => new Promise((resolve, reject) => { | |
const video = document.createElement('video'), | |
timeout = t && setTimeout(() => { | |
video.src = "//!!!/timeout"; | |
reject("Video timed out."); | |
}, t); | |
video.preload = "metadata"; | |
video.onloadedmetadata = e => { | |
timeout && clearTimeout(timeout); | |
resolve(e.target); | |
}; | |
video.onerror = e => { | |
timeout && clearTimeout(timeout); | |
reject(e); | |
}; | |
video.src = href; | |
}) | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment