Last active
December 25, 2015 09:59
-
-
Save Xeus/6958649 to your computer and use it in GitHub Desktop.
JS Assert for Input Checking
This file contains 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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsfiddle.net/xeus/WvDwY/