This code creates a function toParams that replaces all instances of a ? with a & . Then the code creates a function toQuery that takes the params array and the delimiter string as arguments. The code loops through the params array and for each key it splits the key value using the equals operator (=). It then assigns the value from the params[key] variable to the query variable. Next, it checks to see if there is an index value less than the keys.length - 1 . If there is an index less than keys.length - 1 then the code appends the delimiter string to the query variable. Finally, the code returns the stringified version of the query variable.

    Library: react

    export function toParams(query) {
      const q = query.replace(/^\??\//, '');
      return q.split('&').reduce((values, param) => {
        const [key, value] = param.split('=');
        values[key] = value;
        return values;
      }, {});
    export function toQuery(params, delimiter = '&') {
      const keys = Object.keys(params);
      return keys.reduce((str, key, index) => {
        let query = `${str}${key}=${params[key]}`;
        if (index < keys.length - 1) {
          query += delimiter;
        return query;
      }, '');
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.