Created
November 8, 2017 04:20
-
-
Save skyjur/ca0ca2ba21d3ee8bae293225e8b1463c to your computer and use it in GitHub Desktop.
js utils
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 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