-4

Please offers JavaScript language solution

Here is the Apple interview question:

input: http://www.apple.com?a=1&b=2&c=3

output:

{
 a:1,
 b:2,
 c:3
}

How to solve this question without hard code? and

If I don't know URL constructor concept, any other solution to solve this problem?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Lyon
  • 21
  • 1
  • 5

2 Answers2

1

That part of the URL you're looking for is called query string. There are lots of libraries in programming languages that can parse the URL and get those parameters.

Here is a Python solution:

With urllib.parse module you can parse(urlparse) a URL and get the information from its query string(parse_qs).

from urllib.parse import urlparse, parse_qs

url = "http://www.apple.com?a=1&b=2&c=3"
parsed_url = urlparse(url)
d = {k: v[0] for k, v in parse_qs(parsed_url.query).items()}

print(d)

output:

{'a': '1', 'b': '2', 'c': '3'}

the [0] part is because the values of the dictionary returned from the parse_qs is a list. So we get its (first) item.

S.B
  • 13,077
  • 10
  • 22
  • 49
0

Here's a JavaScript solution. By using the URL constructor on the link, you can easily access its parameters.

const urlParamsToObject = (link) => {
    const url = new URL(link);

    return Object.fromEntries(url.searchParams.entries());
};

console.log(urlParamsToObject('http://www.apple.com?a=1&b=2&c=3'));

Is this really an Apple interview question?

EDIT:

It's also possible to do this without the URL constructor. Here's an example of that in TypeScript:

const urlParamsToObject = (link: string) => {
    const searchParams = link.split('?')[1].split('&');

    return searchParams.reduce<Record<string, string>>((acc, curr) => {
        const [key, val] = curr.split('=');

        return {
            ...acc,
            [key]: decodeURIComponent(val),
        };
    }, {});
};

console.log(urlParamsToObject('http://www.apple.com?a=1&b=2&c=3'));

And here's an example in Python:

from urllib.parse import unquote

def url_to_params_object (link: str):
    search_params = link.split('?')[1].split('&')

    return { str.split('=')[0]: unquote(str.split('=')[1]) for str in search_params }

print(url_to_params_object('http://www.apple.com?a=1&b=2&c=3'))
mstephen19
  • 1,733
  • 1
  • 5
  • 20