Skip to content

Commit 9b78cfc

Browse files
authored
Merge pull request neetcode-gh#1622 from loczek/0535-encode-and-decode-tinyurl
Create: 0535-encode-and-decode-tinyurl.ts
2 parents 8fd804c + d3cf047 commit 9b78cfc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const encodeMap = {};
2+
const decodeMap = {};
3+
let size = 0;
4+
5+
/**
6+
* Encodes a URL to a shortened URL.
7+
*/
8+
function encode(longUrl: string): string {
9+
if (!encodeMap.hasOwnProperty(longUrl)) {
10+
let shortUrl = size + 1;
11+
size += 1;
12+
encodeMap[longUrl] = shortUrl;
13+
decodeMap[shortUrl] = longUrl;
14+
}
15+
16+
return encodeMap[longUrl];
17+
}
18+
19+
/**
20+
* Decodes a shortened URL to its original URL.
21+
*/
22+
function decode(shortUrl: string): string {
23+
return decodeMap[shortUrl];
24+
}
25+
26+
/**
27+
* Your functions will be called as such:
28+
* decode(encode(strs));
29+
*/

0 commit comments

Comments
 (0)