考点: URLSearchParamsmap生成器函数

    1. class MyURLSearchParams {
    2. // map;
    3. /**
    4. * @params {string} init
    5. */
    6. constructor(init) {
    7. this.map = new Map();
    8. let arr = init.replace(/^\?/, '').split(/\&/);
    9. for (let item of arr) {
    10. let [k, v] = item.split('=');
    11. if (this.map.has(k)) {
    12. this.append(k, v);
    13. } else {
    14. this.set(k, v);
    15. }
    16. }
    17. }
    18. /**
    19. * @params {string} name
    20. * @params {any} value
    21. */
    22. append(name, value) {
    23. this.map.get(name).push(String(value));
    24. }
    25. /**
    26. * @params {string} name
    27. */
    28. delete(name) {
    29. this.map.delete(name);
    30. }
    31. /**
    32. * @returns {Iterator}
    33. */
    34. * entries() {
    35. for (let [k, values] of this.map) {
    36. for (let val of values) {
    37. yield [k, val]
    38. }
    39. }
    40. }
    41. /**
    42. * @param {(value, key) => void} callback
    43. */
    44. forEach(callback) {
    45. for (let [k, values] of this.map) {
    46. for (let val of values) {
    47. callback(val, k)
    48. }
    49. }
    50. }
    51. /**
    52. * @param {string} name
    53. * returns the first value of the name
    54. */
    55. get(name) {
    56. return this.map.has(name) ? this.map.get(name)[0] : null;
    57. }
    58. /**
    59. * @param {string} name
    60. * @return {string[]}
    61. * returns the value list of the name
    62. */
    63. getAll(name) {
    64. return this.map.has(name) ? this.map.get(name): [];
    65. }
    66. /**
    67. * @params {string} name
    68. * @return {boolean}
    69. */
    70. has(name) {
    71. return this.map.has(name);
    72. }
    73. /**
    74. * @return {Iterator}
    75. */
    76. keys() {
    77. return this.map.keys();
    78. }
    79. /**
    80. * @param {string} name
    81. * @param {any} value
    82. */
    83. set(name, value) {
    84. this.map.set(name, [String(value)])
    85. }
    86. // sor all key/value pairs based on the keys
    87. sort() {
    88. this.map = new Map([...this.map].sort());
    89. }
    90. /**
    91. * @return {string}
    92. */
    93. toString() {
    94. let ans = [];
    95. for (let [k, values] of this.map) {
    96. for (let val of values) {
    97. ans.push(`${k}=${val}`);
    98. }
    99. }
    100. return ans.join('&');
    101. }
    102. /**
    103. * @return {Iterator} values
    104. */
    105. * values() {
    106. for (let [k, values] of this.map) {
    107. for (let val of values) {
    108. yield val
    109. }
    110. }
    111. }
    112. }