uci-utils-type/src/check.js

56 lines
1.8 KiB
JavaScript

import * as typechecker from 'typechecker'
import observable from 'is-observable'
// TODO add observable types and other custom uci types
const customTypeChecker = Object.assign({}, typechecker) // typechecker is frozen
// add custom types
customTypeChecker.isPromise = function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
customTypeChecker.isBuffer = function isBuffer(obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
customTypeChecker.isSymbol = function isSymbol(x) {
return typeof x === 'symbol'
|| typeof x === 'object' && Object.prototype.toString.call(x) === '[object Symbol]';
}
customTypeChecker.isObservable = observable
customTypeChecker.isEmitter = function isEmitter(emitter) {
if (!emitter) return false
let check = ['on', 'emit']
return check.reduce((acc, fn) => acc && typeof emitter[fn] === 'function', true)
}
customTypeChecker.isAsync = function isAsync(fn) {
if (typeof fn !== 'function') return false
return (customTypeChecker.isPromise(fn) || fn.constructor.name === 'AsyncFunction')
}
// Add custom types to typeMap
let customTypeMap = {
buffer: customTypeChecker.isBuffer,
promise: customTypeChecker.isPromise,
symbol: customTypeChecker.isSymbol,
observable: customTypeChecker.isObservable,
emitter: customTypeChecker.isEmitter,
async: customTypeChecker.isAsync
}
customTypeMap = Object.assign(customTypeMap, customTypeChecker.typeMap)
customTypeChecker.getType = function customGetType(value, _typeMap) {
return typechecker.getType(value, _typeMap || customTypeMap)
}
const typeOf = customTypeChecker.getType
export default customTypeChecker
export { customTypeChecker as check, typeOf }