Skip to content

Instantly share code, notes, and snippets.

@WebMaestroFr WebMaestroFr/url.js

Last active Feb 23, 2018
Embed
What would you like to do?
URL Parser and Media Promise
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
You can’t perform that action at this time.