Skip to content

Instantly share code, notes, and snippets.

@Xeus
Last active December 25, 2015 09:59
Show Gist options
  • Save Xeus/6958649 to your computer and use it in GitHub Desktop.
Save Xeus/6958649 to your computer and use it in GitHub Desktop.
JS Assert for Input Checking
var assert = function(condition, msg) {
if (!condition) {
// throw message || "Assertion failed";
console.log('FAIL ----- ' + msg);
}
else {
console.log('PASS ----- ' + msg);
}
};
var testNum = function(input) {
if (!isNaN(input) && input !== null) {
return Number(input) * 2;
}
else {
return null;
}
};
var testStr = function(input) {
if (typeof(input) === 'string') {
return input.slice(0);
}
if (typeof(input) === 'number' && !isNaN(input)) {
return String(input).slice(0);
}
else {
return null;
}
};
var assertAll = function(testType, testFunc, optional) {
console.log('Running asserts...');
var vals = [5, 'hi', '5', null, undefined, -5, NaN, [], ['hi'], {}];
for (var i=0; i<vals.length; i++) {
var result = testFunc(vals[i]);
assert(testType === typeof(result) || result === optional, 'Input: ' + String(vals[i]) + '. Result: ' + result);
}
};
assertAll('number', testNum, null);
assertAll('string', testStr, null);
@Xeus
Copy link
Author

Xeus commented Oct 13, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment