mtype
A type checking facade that doesn't care how you check types - use duck typing, use JSON schema, whatever.
I needed a consistent interface for type checking, sometimes I use duck typing, sometimes I use JSON schema, regardless of which I tend to follow the same general pattern, mtype codifies this.
usage
const T = const predicates = // T(predicates:Object[Any=>Boolean])=>facade:Object[Function]// create an instance of the type facadeconst t = // is(subject:Any,typename:String)=>matchesType:Boolean// subject passes test for type?console // isOnly(subject:Any,typename:String)=>matchesType:Boolean// subject passes test for type and doesn't pass any othersconsole // some(subject:Any,typenames:...String)=>matchesSome:Boolean// subject matches at least one of the required typesconsole // every(subject:Any,typenames:...String)=>matchesAll:Boolean// subject matches all of the required typesconsole // of(subject:Any)=>typename:String// find best single type for subjectconsole // allOf(subject:Any)=>typenames:[String]// find all types that the subject passesconsole
what I usually use this for
Performing different actions depending on the type of something. Example using DOM nodes:
const predicates = nodenodeType === 3 nodenodeType === 8 // etc const toString = nodenodeValue '<!--' + nodenodeValue + '-->' // etc const t = const nodeToString = { const typename = t const stringifier = toString typename return }
named predicates
Write some functions that return true if the passed arg is the named type. They
are checked in the order that the keys were declared in the named predicates
object, so order them from most to least specific. For example, in the following
example an array will pass both the array
and object
test, so array
should
come first:
const predicates = Array typeof subject === 'object' const t = console // "array"console // trueconsole // [ "array", "object" ]
default types
If you instantiate without any predicates, it defaults to the types that I test most often, which are JSON types:
const t = console // "array"
Note that there are some differences between JSON types and JavaScript types, for example in JavaScript an array is considered to be both an object and an array, whereas in JSON it is only an array.
license
MIT