The task is to implement a function that determines the type of data.
The boilerplate code
function detectType(data) {
// your code here
}
The process involved in determining the type of data is to check for all kinds of data types. To check if the data is null
if(data === null) return 'null';
To check if the data is a number
if(data instanceof Number) return 'number';
To check if the data is a string
if(data instanceof String) return 'string';
To check if the data is a boolean
if(data instanceof Boolean) return 'boolean';
To check if the data is a date
if(data instanceof Date) return 'date';
To check if the data is a regular expression
if(data instanceof RegExp) return 'regexp';
To check if the data is a set
if(data instanceof Set) return 'set';
To check if the data is a map
if(data instanceof Map) return 'map';
To check if the data is a function
if(data instanceof Function) return 'function';
To check if the data is an array
if(Array.isArray(data)) return 'array';
To check if the data is an array buffer
if(data instanceof ArrayBuffer) return 'arraybuffer';
To check if the data is primitive
const type = typeof data;
if (type !== 'object') return type;
All data types have been accounted for. The final code
function detectType(data) {
// your code here
if(data === null) return 'null';
if(data instanceof String) return 'string';
if(data instanceof Number) return 'number';
if(data instanceof Boolean) return 'boolean';
if(Array.isArray(data)) return 'array';
if(data instanceof Date) return 'date';
if(data instanceof RegExp) return 'regexp';
if(data instanceof Map) return 'map';
if(data instanceof Set) return 'set';
if(data instanceof Function) return 'function';
if(data instanceof ArrayBuffer) return 'arraybuffer';
const type = typeof data;
if(type !== 'object') return type;
return typeof data;
}
That's all folks!
Top comments (0)