1
+ // src/04-stack/decimal-to-base.js
2
+
3
+ import Stack from './stack' ;
4
+
5
+ /**
6
+ * Converts a decimal number to a given base
7
+ * @param {number } decimalNumber - decimal number to be converted
8
+ * @param {number } base - base to convert the decimal number to
9
+ * @returns {string } base representation of the decimal number
10
+ */
11
+ function decimalToBase ( decimalNumber : number , base : number ) {
12
+
13
+ if ( base < 2 || base > 36 ) {
14
+ throw new Error ( 'Base must be between 2 and 36' ) ;
15
+ }
16
+
17
+ const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ; // Digits for base 36
18
+ const remainderStack = new Stack < number > ( ) ;
19
+ let baseString = '' ;
20
+
21
+ while ( decimalNumber > 0 ) {
22
+ const remainder = Math . floor ( decimalNumber % base ) ;
23
+ remainderStack . push ( remainder ) ;
24
+ decimalNumber = Math . floor ( decimalNumber / base ) ;
25
+ }
26
+
27
+ while ( ! remainderStack . isEmpty ( ) ) {
28
+ baseString += digits [ remainderStack . pop ( ) ] ; // Use digit mapping
29
+ }
30
+
31
+ return baseString ;
32
+ }
33
+
34
+ /**
35
+ * Converts a decimal number to a given base
36
+ * @param {number } decimalNumber - decimal number to be converted (between 2 and 36 or 64)
37
+ * @param {number } base - base to convert the decimal number to
38
+ * @returns {string } base representation of the decimal number
39
+ */
40
+ function decimalToBase64 ( decimalNumber : number , base : number ) {
41
+ if ( base < 2 || ( base > 36 && base !== 64 ) ) {
42
+ throw new Error ( 'Base must be between 2 and 36 or 64' ) ;
43
+ }
44
+
45
+ const digits = base === 64 ?
46
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' :
47
+ '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ;
48
+
49
+ const remainderStack = new Stack < number > ( ) ;
50
+ let baseString = '' ;
51
+
52
+ while ( decimalNumber > 0 ) {
53
+ const remainder = Math . floor ( decimalNumber % base ) ;
54
+ remainderStack . push ( remainder ) ;
55
+ decimalNumber = Math . floor ( decimalNumber / base ) ;
56
+ }
57
+
58
+ while ( ! remainderStack . isEmpty ( ) ) {
59
+ baseString += digits [ remainderStack . pop ( ) ] ;
60
+ }
61
+
62
+ // Handle padding for Base64 (if necessary)
63
+ /* Base64 encodes data in groups of 3 bytes (24 bits).
64
+ Each group is represented by four Base64 characters (6 bits per character).
65
+ If the input data length isn't divisible by 3, padding characters (=) are added to the end of the output
66
+ to ensure that the total length is a multiple of 4.
67
+ This is important for proper decoding of the Base64 string back to its original data. */
68
+ if ( base === 64 ) {
69
+ while ( baseString . length % 4 !== 0 ) {
70
+ baseString += '=' ;
71
+ }
72
+ }
73
+
74
+ return baseString ;
75
+ }
76
+
77
+ export { decimalToBase , decimalToBase64 } ;
0 commit comments