Skip to content

Commit 44f4d73

Browse files
author
Wakidur Rahaman
committed
encodeId
1 parent 6acaeab commit 44f4d73

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/exercises/string/shortening.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,29 @@
55
* There are 62 possible letters and numbers,
66
* consisting of 26 lowercase letters, 26 uppercase letters, and 10 numbers (0 to 9).
77
*/
8+
9+
const DICTIONARY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split('');
10+
11+
function encodeId(id: number) {
12+
const base = DICTIONARY.length;
13+
let encoded: string | number = '';
14+
15+
if (id === 0) {
16+
return DICTIONARY[0];
17+
}
18+
19+
while (id > 0) {
20+
encoded += DICTIONARY[id % base];
21+
id = Math.floor(id / base);
22+
}
23+
24+
return reverseWord(encoded);
25+
}
26+
27+
function reverseWord(str: string) {
28+
let reversed: string = '';
29+
for (let i = str.length - 1; i >= 0; i--) {
30+
reversed += str.charAt(i);
31+
}
32+
return reversed;
33+
}

0 commit comments

Comments
 (0)