1
+ const d2f = num => {
2
+ const helper = ( f1 , f2 , n ) => {
3
+ if ( f2 > n ) {
4
+ return [ n , "1" ] ;
5
+ }
6
+ [ rem , b ] = helper ( f2 , f1 + f2 , n ) ;
7
+ if ( rem >= f2 ) {
8
+ return [ rem - f2 , "1" + b ] ;
9
+ } else {
10
+ return [ rem , "0" + b ] ;
11
+ }
12
+ }
13
+ if ( num <= 0 ) {
14
+ return "Number must be greater than 0" ;
15
+ }
16
+ return helper ( 1 , 1 , num ) [ 1 ] ;
17
+ } ;
18
+
19
+ const f2d = b => {
20
+ const helper = ( f1 , f2 , i ) => {
21
+ if ( i >= b . length - 1 ) {
22
+ return 0 ;
23
+ }
24
+ const char = b . charAt ( i ) ;
25
+ if ( char == '1' ) {
26
+ return f2 + helper ( f2 , f1 + f2 , i + 1 ) ;
27
+ } else if ( char == '0' ) {
28
+ return helper ( f2 , f1 + f2 , i + 1 ) ;
29
+ }
30
+ }
31
+ for ( var i = 0 ; i < b . length ; i ++ ) {
32
+ switch ( b . charAt ( i ) ) {
33
+ case '1' :
34
+ case '0' :
35
+ break ;
36
+ default :
37
+ return `Invalid character at position ${ i } : ${ b . charAt ( i ) } ` ;
38
+ }
39
+ }
40
+ if ( b . length < 2 || b . charAt ( b . length - 1 ) != '1' || b . charAt ( b . length - 2 ) != '1' ) {
41
+ return "Last two bits must be 1" ;
42
+ }
43
+ return helper ( 1 , 1 , 0 ) ;
44
+ } ;
45
+
46
+ document . getElementById ( "d2f" ) . addEventListener ( "click" , ( ) => {
47
+ const input = document . getElementById ( "input" ) . value ;
48
+ const output = d2f ( parseInt ( input ) ) ;
49
+ document . getElementById ( "output" ) . value = output ;
50
+ } ) ;
51
+ document . getElementById ( "f2d" ) . addEventListener ( "click" , ( ) => {
52
+ const input = document . getElementById ( "input" ) . value ;
53
+ const output = f2d ( input ) ;
54
+ document . getElementById ( "output" ) . value = output . toString ( ) ;
55
+ } ) ;
0 commit comments