Created
October 28, 2014 05:11
-
-
Save Karlina-Bytes/e7198f2cf78dd918cd74 to your computer and use it in GitHub Desktop.
JavaScript functions for validating user input for a base converter applet.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************************* | |
* Removes space characters from the input string. | |
* Sets any letters in the input string to uppercase. | |
* @param {String} inputString | |
* @return {String} "cleaned up" inputString. | |
*********************************************************/ | |
function sanitizeInput( inputString ) { | |
// If the inputString is empty, return an error. | |
if (!inputString) return "Error"; | |
// Remove space characters. | |
var modifiedString = ""; | |
for (var i in inputString) | |
if (inputString[i] != " ") | |
modifiedString += inputString[i]; | |
// Set letters to uppercase. Return result. | |
return modifiedString.toUpperCase(); | |
} | |
/********************************************************* | |
* Checks whether a given string represents a number of | |
* the given base. For example, 1101 is base 2. | |
* @param {String} digitString | |
* @param {String} base | |
* @return {Boolean} true if digitString matches base | |
********************************************************/ | |
function numberAndBaseMatch( digitString, base ) { | |
// Determine the cardinality of the digitSet. | |
var digitSet = ['0']; | |
var letterDigits = ['A','B','C','D','E']; | |
for (var i = 2; i <= 16; i++) { | |
// Add digits 0 through 9 as needed. | |
if (i <= 10) { | |
digitSet.push( (i - 1).toString().charAt(0) ); | |
if (parseInt(base) == i) break; | |
} | |
// Add digits A through F as needed. | |
else { | |
digitSet.push( letterDigits[i - 11] ); | |
if (parseInt(base) == i) break; | |
} | |
} | |
// Check whether inputString chars are digitSet members. | |
for (var i in digitString) { | |
var charMatch = false; | |
for (var k in digitSet) { | |
if (digitString[i] == digitSet[k]) charMatch = true; | |
} | |
if (!charMatch) return false; | |
} | |
// Return true if inputString matches inputBase. | |
return true; | |
} | |
/********************************************************* | |
* Displays an output message on the webpage. | |
* @param {String} message to display | |
********************************************************/ | |
function displayResult( message ) { | |
var resultArea = document.getElementById("resultArea"); | |
var content = ("<h4><em>" + message + "</em></h4>"); | |
resultArea.innerHTML = content; | |
resultArea.style.display = "block"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment