Created
July 20, 2020 16:24
-
-
Save exbotanical/43a948e62ad9e1d7bd0ff9446b2c4bcb to your computer and use it in GitHub Desktop.
code golf, FP and Objects edition!
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
| class UriBuilder { | |
| constructor(uri) { | |
| this.root = uri; | |
| this.url = this.root.split("?"); | |
| this.params = {}; | |
| UriBuilder.populate.apply(this); | |
| }; | |
| static populate() { | |
| if (!this.url.length < 2) { | |
| return this.url[1] | |
| .split("&") | |
| .map(i => i.split("=")) | |
| .forEach(([key, value]) => this.params[key] = value); | |
| } | |
| }; | |
| build() { | |
| const params = Object.entries(this.params); | |
| if (!params.length) { | |
| return this.root; | |
| } | |
| const x = []; | |
| params.forEach(([key, value], index) => { | |
| if (value) { | |
| x.push(`${index > 0 ? "&" : ""}${key}=${String(value).split(" ").join("%20")}`); | |
| } | |
| }); | |
| return `${this.url[0]}?${x.join("")}`; | |
| } | |
| }; | |
| /* | |
| Prompt | |
| "Create a basic UriBuilder object that will be used specifically to build query params on an existing URI. | |
| It should support a params property and a build method. It will handle the URL having pre-existing params that need to be managed. | |
| The URL must be properly encoded (i.e. "a b" should be encoded as "a%20b")" | |
| Bonus: Cannot use *any* of the built-in `uri` methods. | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment