samchon / typia

Super-fast/easy runtime validators and serializers via transformation
https://typia.io/
MIT License
4.47k stars 154 forks source link

What does ` if (RegExp(/^-?\d+\.?\d*$/).test(key))` do? #746

Closed japrescott closed 1 year ago

japrescott commented 1 year ago

Question

Hey @samchon

Thanks a lot for creating this cool library!

I was looking at the generated code and have come across this piece of code a lot: if (RegExp(/^-?\d+\.?\d*$/).test(key))

And was wondering why this is done for every key? If its needed, one could improve speed by reusing the regex?

I can understand this check for certain objects (e.g Record<string, any) but also see it used for arrays where you Object.keys().every instead of directly using Array.every. Checking the key of an array should not be necessary?

Would be interesting to learn why you made the aforementioned choices? Otherwise happy to make a PR.

Thanks again for the great library.

/Edit: I just realized this is only the case because my interface is weird

interface Thing extends array<number> {
}

interface Obj {
   myArray: Thing
}

Is there a way in the type system to detect something extending from an array? Or is it always considered as an object?

samchon commented 1 year ago

Why are you extending Array? Don't do that.

If you extends the Array class and add a property, JS will handles it as an object type, so that JSON.stringify would be returned like below. Of course, its performance would be dramatically slow as your custom class would be composed with HashMap instance for dynamic key insertions/deletions.

{
   "someAdditionalProperty": "something",
   "0": "someVaue",
   "1": "otherValue"
}
japrescott commented 1 year ago

Thank you for your reply. We are using openapi spec and generate the interface via openapi-generator-cli. If we $ref something that is an array, it creates that interface and am currently trying to figure out how I can get it to generate it the correct way.

Thanks again

samchon commented 1 year ago

This article may be helpful to understand the reason why Array extended object is no more Array.

https://dev.to/samchon/secret-of-typia-how-it-could-be-20000x-faster-validator-hidden-class-optimization-in-v8-engine-1mfb