DEV Community

Alaa Mohammad
Alaa Mohammad

Posted on

2

Create a custom function to generate a URL from given parameters (with TS support) 💻

We can achieve this using two options:

First option:

const urlGenerator = (
    baseUrl: string,
    pathName: string,
    searchParamsArray: Array<Record<string, string | number>>
  ) => {
    const validSearchParams = searchParamsArray.filter((param) => {
      const [_, value] = Object.entries(param)[0];
      // We can put here any condition on the value
      return value;
    });
    const sortedSearchParams = validSearchParams.sort((a, b) => {
      const [aKey] = Object.entries(a)[0];
      const [bKey] = Object.entries(b)[0];
      if (aKey > bKey) {
        return 1;
      } else if (aKey < bKey) {
        return -1;
      } else return 0;
    })
    const searchParams = sortedSearchParams
      .map((param) => {
        const [key, value] = Object.entries(param)[0];
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      })
      .join("&");
    const url = `${baseUrl}${pathName}?${searchParams}`;
    return url;
  };
  const resultUrl = urlGenerator("http://example.com", "/", [
    { width: 200 },
    { height: 250 },
    { locale: "en" },
    { toolbar_bg: "" },
    { interval: "3h" },
    { search: "react19" },
  ]);
  console.log("resultUrl=", resultUrl);

// resultUrl= http://example.com/?height=250&interval=3h&locale=en&search=react19&width=200
Enter fullscreen mode Exit fullscreen mode

Second option:
By using URLSearchParams as the following

const urlGenerator = (
    baseUrl: string,
    pathName: string,
    searchParamsArray: Array<Record<string, string>>
  ) => {
    const validSearchParams = searchParamsArray.filter((param) => {
      const [_, value] = Object.entries(param)[0];
      // We can put here any condition on the value
      return value;
    });
    const sortedSearchParams = validSearchParams.sort((a, b) => {
      const [aKey] = Object.entries(a)[0];
      const [bKey] = Object.entries(b)[0];
      if (aKey > bKey) {
        return 1;
      } else if (aKey < bKey) {
        return -1;
      } else return 0;
    }).map((param)=>Object.entries(param)[0]);
    const searchParams=new URLSearchParams(Object.fromEntries(sortedSearchParams))
    const url = `${baseUrl}${pathName}?${searchParams.toString()}`;
    return url;
  };
  const resultUrl = urlGenerator("http://example.com", "/", [
    { width: "200" },
    { height: "250" },
    { locale: "en" },
    { toolbar_bg: "" },
    { interval: "3h" },
    { search: "react19" },
  ]);
  console.log("resultUrl=", resultUrl); 
// resultUrl= http://example.com/?height=250&interval=3h&locale=en&search=react19&width=200

Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay