tapjs/tcompare

Custom comparator support?

Closed this issue · 3 comments

E.g. for match it works as:

typeof pattern === 'function' && typeof obj === 'object'
        ? obj instanceof pattern

which just checks for instanceof and is totally fine, but in JS things could be dynamic.

If I want to check if obj here is either a specific object or a string I have to test it separately from match function.

What I could propose is use of special classes like Either, Neither, e.g.:

t.match(subj, {
  stringOrObj: t.match.either([String, Object]),
  notAnObject: t.match.neither([Object]),
})

t.match.either and t.match.neither would produce instances of internal classes Neither or Either, which should allow for explicit branching of match algorythm.

I like it. Not sure if I'm sold on the sub-function being exported as a member of t.match, since that would complicate the class definition somewhat, but some kind of way of expressing this would be nice. (Maybe just t.either(...) and t.neither(...)?)

Either and Neither classes should be exported by this module, and handled by the matching classes (Same, Strict, Has, HasStrict, and Match). Patch welcome!

@isaacs awesome, will take it as soon as I have time, will update here.

On second though, it should probably just be a t.either(obj, one, two) and t.neither(a, one, two) function in tap itself, since it'll just call tmatch.match() on either object and return true/false if one of them matches. Don't need the logic in this module.