Skip to content

Instantly share code, notes, and snippets.

@myfreeer
Last active April 28, 2018 03:19
Show Gist options
  • Save myfreeer/d805427aba19f5b34480edafeb94e20d to your computer and use it in GitHub Desktop.
Save myfreeer/d805427aba19f5b34480edafeb94e20d to your computer and use it in GitHub Desktop.
URLSearchParams polyfill in es6, licensed MIT
class URLSearchParams {
constructor(str) {
if (str) this._parse(str);
}
_getStr(key) {
return Array.isArray(this[key]) ? this[key].map(value => `${key}=${encodeURIComponent(value)}`).join('&') : `${key}=${encodeURIComponent(this[key])}`;
}
_parse(str) {
if (!str) return false;
if (str.charAt(0) === '?') str = str.substr(1);
str.split('&').map(e => e.split('=')).forEach(e => this.append(e[0], e[1]));
return this;
}
append(key, value) {
value = decodeURIComponent(value);
if (this.has(key))
this[key] = [].concat(this[key]).concat(value);
else this[key] = value;
}
delete(name) {
delete this[name];
}
entries() {
const arr = [];
for (const key of this.keys()) {
if (Array.isArray(this[key]))
this[key].forEach(value => arr.push(key, value));
else arr.push([key, this[key]]);
}
return arr;
}
get(name) {
return Array.isArray(this[name]) ? this[name][0] : this[name];
}
getAll(name) {
return [].concat(this[name]);
}
has(name) {
return this.hasOwnProperty(name);
}
keys() {
return Object.keys(this);
}
set(name, value) {
this[name] = decodeURIComponent(value);
}
toString(keys = this.keys()) {
keys = keys && keys.map ? keys.filter(e => this.has(e)) : this.keys();
return keys.map(e => this._getStr(e)).join('&');
}
values() {
return this.entries().map(e => e[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment