Skip to content

Instantly share code, notes, and snippets.

@skyjur
Created November 8, 2017 04:20
Show Gist options
  • Select an option

  • Save skyjur/ca0ca2ba21d3ee8bae293225e8b1463c to your computer and use it in GitHub Desktop.

Select an option

Save skyjur/ca0ca2ba21d3ee8bae293225e8b1463c to your computer and use it in GitHub Desktop.
js utils
export function getPath(url: string) {
return url
.replace(/^(http[s]?:)?\/\/[^/#?]+/, '') // remove origin
.replace(/[?#].*$/, '') // remove querystring or hash
}
export function getUrlParams(url: string) : {[key: string]: string} {
if(url.indexOf('?') !== -1) {
return parseQueryString(url.split('?')[1]);
} else {
return {};
}
}
export function parseQueryString(query: string) : {[key: string]: string} {
let params: {[key: string]: string} = {};
for(let v of query.split('&')) {
let [key, val=""] = v.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(val);
}
return params;
}
/**
* Given a promise returns a promise, which never fails, and returns
* either [result, null] on success or [null, error] on failure
*
* Allows to write code which looks like
*
* let data, error; try { data = await X } catch (e) { error = e; }
*
* Shorter:
*
* let [data, error] = await withError(X);
*/
export function withError<T>(promise: Promise<T>) : Promise<[T, null] | [null, Error]> {
return new Promise((done) => {
this.then((result: T) => done([result, null]));
this.catch((error: Error) => done([null, error]));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment