Created
December 21, 2021 19:36
-
-
Save D1360-64RC14/5d7f1c7676c8506df7040b1d93f51cc1 to your computer and use it in GitHub Desktop.
Implementation of proper FormURLEncoded class in JS
This file contains 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 FormURLEncoded extends Map { | |
/** | |
* @param {Nullable<String>} formString - Form URL encoded string (ex: `'hello=world&foo=bar&tar=gz'`) | |
*/ | |
constructor(formString = null) { | |
super(formString ? | |
formString | |
.trim() | |
.split('&') | |
.map( | |
element => element.split('=').map(decodeURIComponent) | |
) | |
: undefined | |
); | |
} | |
/** | |
* Translate the Map to a form URL encoded string | |
* @returns {String} | |
*/ | |
toString() { | |
return Array.from(this) | |
.map( | |
element => element.map(encodeURIComponent).join('=') | |
) | |
.join('&') | |
; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment