考点: URLSearchParams、map、生成器函数
class MyURLSearchParams {
// map;
/**
* @params {string} init
*/
constructor(init) {
this.map = new Map();
let arr = init.replace(/^\?/, '').split(/\&/);
for (let item of arr) {
let [k, v] = item.split('=');
if (this.map.has(k)) {
this.append(k, v);
} else {
this.set(k, v);
}
}
}
/**
* @params {string} name
* @params {any} value
*/
append(name, value) {
this.map.get(name).push(String(value));
}
/**
* @params {string} name
*/
delete(name) {
this.map.delete(name);
}
/**
* @returns {Iterator}
*/
* entries() {
for (let [k, values] of this.map) {
for (let val of values) {
yield [k, val]
}
}
}
/**
* @param {(value, key) => void} callback
*/
forEach(callback) {
for (let [k, values] of this.map) {
for (let val of values) {
callback(val, k)
}
}
}
/**
* @param {string} name
* returns the first value of the name
*/
get(name) {
return this.map.has(name) ? this.map.get(name)[0] : null;
}
/**
* @param {string} name
* @return {string[]}
* returns the value list of the name
*/
getAll(name) {
return this.map.has(name) ? this.map.get(name): [];
}
/**
* @params {string} name
* @return {boolean}
*/
has(name) {
return this.map.has(name);
}
/**
* @return {Iterator}
*/
keys() {
return this.map.keys();
}
/**
* @param {string} name
* @param {any} value
*/
set(name, value) {
this.map.set(name, [String(value)])
}
// sor all key/value pairs based on the keys
sort() {
this.map = new Map([...this.map].sort());
}
/**
* @return {string}
*/
toString() {
let ans = [];
for (let [k, values] of this.map) {
for (let val of values) {
ans.push(`${k}=${val}`);
}
}
return ans.join('&');
}
/**
* @return {Iterator} values
*/
* values() {
for (let [k, values] of this.map) {
for (let val of values) {
yield val
}
}
}
}