You can send in ANY THING to the identify()
function and it returns an object with 2 properties: .type
& .subType
that lets you identify whatever it was you sent in.
eg: identify([]).subType
returns: "array"
instead of "object"
that typeof
would return.
.type
is the same as typeof
in case you need a more general matching, but .subType
tries to be as specific as posible, you usually want to use .subType
.
All output strings will always be turned to lowercase, for consistency & ease of writing.
This is great when working with larger projects &/or global variables, where the variable you get into a function might not be what you expec it to be, because some other function have changed the value, or someone sends the wrong data to your function.
Eg: You get in: add("1", 2)
& return "12"
instead of 3
.
npm i sn-identify
or:
npm install @sebbes/identify
(same files, use whichever you like best)
let foo = identify( null );
console.log( foo.type ); // "object"
console.log( foo.subType ); // "null"
if( foo.subType === "null" ) {
foo = 5;
}
let bar = identify( 3.14 );
console.log( typeof bar ); // "object"
console.log( bar.type ); // "number"
console.log( bar.subType ); // "float"
/*
bar = {
type: "number",
subType: "float"
}
*/
let baz = new Date();
let qux = identify( baz );
/*
qux = {
type: "object ",
subType: "date"
}
*/
There is no (known?) way to differentiate a "integer like" float number, eg: 3.00
or 123.0000
from a "true integer" eg: 3
or 123
, not even on a binarry level.
Therefore identify(3.00).subType
will return "int"
instead of "float"
.
All other things should return their correct values.
- I am thinking of removing
.type
& only return.subType
directly as a string, but I will wait to see what your feedback says about it. - If you find anything that doesn't return what you think it should, it would be very usefull if you could report it.