jonschlinkert / kind-of

Get the native JavaScript type of a value, fast. Used by superstruct, micromatch and many others!
https://github.com/jonschlnkert
MIT License
347 stars 38 forks source link

Feature request: restricted type list #29

Closed Izhaki closed 3 years ago

Izhaki commented 4 years ago

It is a common use case to only need to assert on certain types.

For example, I need to know if it's an object or a function and don't care otherwise. Or, I'd like to know if it's an array, object or Map (don't care otherwise).

In the second case, this check may be called with each React rendering during mouse drag - so performance may be important.

Would be nice if the API changes to:

const allTypes = [/* ... */];
function kindOf(val, typeList = allTypes) {
  // ...
}
navaru commented 4 years ago

As you can see from the source, there's isn't a simple way to get the value's type info, what you're asking is a major rewrite.

  if (val === void 0) return 'undefined';
  if (val === null) return 'null';

  var type = typeof val;
  if (type === 'boolean') return 'boolean';

  ...

  if (isArray(val)) return 'array';
  if (isBuffer(val)) return 'buffer';

  ...

  switch (ctorName(val)) {
    case 'Symbol': return 'symbol';
    case 'Promise': return 'promise';
Izhaki commented 4 years ago

So long the logic doesn't depend on the order of checks, I can quickly show you how this can be done (with what I wouldn't consider a 'major rewrite').

If it does depend on the sort order... that will make things slightly more complicated.

Florian-Guillot-Axa commented 3 years ago

Why would this ~allTypes.indexOf(kindOf(val)) not work ? It returns 0 if the type of val does not exists in the allTypes array, <0 otherwise. If you want a boolean, you can add !! before. Does this do what you want ?

Izhaki commented 3 years ago

@Florian-Guillot-Axa

This is about optimisation. The body of kindOf just checks if the val is X, if not if its Y, if not if its Z and so on...

What I'm proposing is only check of the kinds you are interested in.

doowb commented 3 years ago

this check may be called with each React rendering during mouse drag

How fast are you moving that mouse?!?! ... Check out the benchmarks... I feel that this isn't where a performance bottleneck will occur, but if you have any code demonstrating an issue, please share it so someone can take a look.

Izhaki commented 3 years ago

This was just an idea for optimisation. But I understand why its value is low. Closing.