earljs
Version:
Ergonomic, modern and type-safe assertion library
61 lines (60 loc) • 2.29 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFunctionTypeName = exports.getTypeName = exports.getComparedTypeName = void 0;
const isEqual_1 = require("../isEqual");
function getComparedTypeName(value, sibling, type, ignorePrototypes) {
let typeName = getTypeName(value, ignorePrototypes);
const siblingTypeName = getTypeName(sibling, ignorePrototypes);
let isDifferentPrototype = false;
const isSameTypeName = typeName === siblingTypeName;
if (!ignorePrototypes && sibling) {
if (isSameTypeName && Object.getPrototypeOf(value) !== Object.getPrototypeOf(sibling)) {
isDifferentPrototype = true;
}
}
if ((type === 'Object' || type === 'RegExp' || type === 'Array') && typeName === type) {
typeName = undefined;
}
return { typeName, isDifferentPrototype, isSameTypeName };
}
exports.getComparedTypeName = getComparedTypeName;
function getTypeName(value, ignorePrototypes) {
if (typeof value === 'function') {
return getFunctionTypeName(value);
}
else if (typeof value === 'object' && value !== null) {
return ignorePrototypes ? (0, isEqual_1.getCanonicalType)(value) : getPrototypeName(value);
}
}
exports.getTypeName = getTypeName;
function getPrototypeName(value) {
const prototype = Object.getPrototypeOf(value);
if (prototype === Object.prototype) {
return 'Object';
}
const constructor = value.constructor;
if (typeof constructor === 'function' && constructor.prototype === prototype && constructor.name) {
return constructor.name;
}
return '[custom prototype]';
}
function getFunctionTypeName(value) {
const type = getFunctionType(value);
const name = value.name || '[anonymous]';
return `${type} ${name}${type === 'class' ? '' : '()'}`;
}
exports.getFunctionTypeName = getFunctionTypeName;
function getFunctionType(value) {
if (value.toString().startsWith('class')) {
return 'class';
}
switch (value.constructor.name) {
case 'GeneratorFunction':
return 'function*';
case 'AsyncGeneratorFunction':
return 'async function*';
case 'AsyncFunction':
return 'async function';
}
return 'function';
}
;