DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 89

The task is to implement a function that determines the type of data.

The boilerplate code

function detectType(data) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a number

if(data instanceof Number) return 'number';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a string

if(data instanceof String) return 'string';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a boolean

if(data instanceof Boolean) return 'boolean';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a date

if(data instanceof Date) return 'date';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a regular expression

if(data instanceof RegExp) return 'regexp';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a set

if(data instanceof Set) return 'set';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a map

if(data instanceof Map) return 'map';
Enter fullscreen mode Exit fullscreen mode

To check if the data is a function

if(data instanceof Function) return 'function';
Enter fullscreen mode Exit fullscreen mode

To check if the data is an array

if(Array.isArray(data)) return 'array';
Enter fullscreen mode Exit fullscreen mode

To check if the data is an array buffer

if(data instanceof ArrayBuffer) return 'arraybuffer';
Enter fullscreen mode Exit fullscreen mode

To check if the data is primitive

const type = typeof data;
  if (type !== 'object') return type;
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)