Skip to content

Instantly share code, notes, and snippets.

@Karlina-Bytes
Last active August 29, 2015 14:07
Show Gist options
  • Save Karlina-Bytes/cce40544f6836fe8775e to your computer and use it in GitHub Desktop.
Save Karlina-Bytes/cce40544f6836fe8775e to your computer and use it in GitHub Desktop.
A JavaScript function for validating whether a given string of characters represents a number of the given base (binary or decimal).
/*********************************************************
* 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 validateInput( digitString, base ) {
// Determine the cardinality of the digitSet.
var digitSet = [];
if ( base == "2" )
digitSet = ['0', '1'];
else
digitSet = ['0','1','2','3','4','5','6','7','8','9'];
/**
* For each character in digitString,
* check whether the character is a member
* of the digitSet for the given base.
* Return false if not.
*/
for ( var i in digitString ) {
var charMatch = false;
for (var k in digitSet ) {
if ( digitString[i] == digitSet[k] )
charMatch = true;
}
if (!charMatch)
return false;
}
/**
* If all the characters in digitString are
* members of digitSet, then return true.
*/
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment