Skip to content

Instantly share code, notes, and snippets.

@resynth1943
Created May 9, 2019 16:53
Show Gist options
  • Save resynth1943/881cd649040376a8bffe88fdd2dac05a to your computer and use it in GitHub Desktop.
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.
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