Created
May 9, 2019 16:53
-
-
Save resynth1943/881cd649040376a8bffe88fdd2dac05a to your computer and use it in GitHub Desktop.
This code generates files that test if a value has the correct "typeof" value.
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
const fs = require('fs'); | |
const assert = require('assert'); | |
const typeofResults = ['number', 'bigint', 'boolean', 'symbol', 'string', 'object']; | |
typeofResults.forEach(result => { | |
fs.writeFileSync(`./is-${result}.js`, `module.exports = function (x) { | |
return typeof x === '${result}'; | |
}`); | |
}); | |
// # Testing | |
function testType (typePredicate, type, correctValue, incorrectValue) { | |
const moduleName = `is-${type}`; | |
assert(typePredicate(correctValue), `✖ ${moduleName} failed when it should have passed`); | |
assert(!typePredicate(incorrectValue), `✖ ${moduleName} passed when it should have failed`); | |
console.log(`✔ ${moduleName} passed on value tests`); | |
} | |
// Now we need to test each file. | |
typeofResults.forEach(result => { | |
const typePredicate = require(`./is-${result}.js`); | |
switch (result) { | |
case 'number': | |
testType(typePredicate, 'number', 2, ''); | |
break; | |
case 'bigint': | |
testType(typePredicate, 'bigint', 11n, true); | |
break; | |
case 'boolean': | |
testType(typePredicate, 'boolean', true, 2); | |
break; | |
case 'symbol': | |
testType(typePredicate, 'symbol', Symbol('abc'), false); | |
break; | |
case 'string': | |
testType(typePredicate, 'string', '', 2); | |
break; | |
case 'object': | |
testType(typePredicate, 'object', {}, 2); | |
break; | |
// We should never hit this | |
default: | |
throw new Error('invalid type'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment