|
convert(num, base1, base2)
// Main function that accepts input and // calls appropriate functions ///////////////////////////////////////// function convert(num, base1, base2) { if (typeof num == "string") num = num.toUpperCase() if (base1 == base2) return num if (base1 == 10) return toBase(num, base2) if (base2 == 10) return toDec(num, base1) return toBase(toDec(num, base1), base2) }
This function accepts a number in base1, and returns its equivalent in base2. Its primary task is to switch between the various function calls that will do the conversion, and to eliminate unnecessary conversions by detecting special cases a priori.
getTableAttributes()
// Gets table's input ///////////////////////////////////////// function getTableAttributes() { var message = "Enter last number to be converted in the table" var lastNum = parseInt(prompt(message, 15)) if (lastNum != 0) drawTable(lastNum) }
The getTableAttributes() function does exactly that. It asks the user for the last decimal number to be displayed in the table. Since the first number is always 0, the number of rows in the table will be greater by 1. If the user clicks cancel in the prompt box, the prompt() method evaluates to null. As explained in Chapter 5, the null value automatically becomes 0 if it is forced to become a number, as is the case with parseInt() function. The function checks whether or not the user’s input was 0 or cancel (cancel evaluates to null, and parseInt(null) == 0). If the input is valid, the function calls the drawTable function to create the conversion table. drawTable(lastNum)
// Create a conversion table ///////////////////////////////////////// function drawTable(lastNum) { with (document) { lastNum = parseInt(lastNum) write("<TABLE BORDER=3>") write("<TR><TD COLSPAN=8><CENTER><FONT COLOR=purple SIZE=+4>") write("Base Converter</FONT></CENTER></TD></TR>") write("<TR>") for (var k = 2; k <= 16; k = k + 2) { write("<TD><CENTER> Base " + k + " </CENTER></TD>") } write("</TR>") for (var i = 0; i <= lastNum; ++i) { write("<TR>") for (var j = 2; j <= 16; j = j + 2) { write("<TD>" + toBase(i, j) + "</TD>") } write("</TR>") } write("</TABLE>") } }
This function prints the conversion table up to the specified number. The table is formatted by regular HTML tags for tables. The with(document) statement enables us to use write() rather than document.write(). The table consists of eight columns for all even bases between 2 (binary) and 16 (hexadecimal). The toBase() function returns the value for each table cell (it uses the main loop’s counter as its parameter). Do not try to create extremely large tables, because too many executions of the function take a long time and might crash your browser on weak operating systems such as Windows 3.x.
|
|||||||||||||||||||||||||||
With any suggestions or questions please feel free to contact us |