Skip to content

Latest commit

 

History

History
67 lines (49 loc) · 1.27 KB

File metadata and controls

67 lines (49 loc) · 1.27 KB

20. Detect data type in JavaScript

Problem

https://bigfrontend.dev/problem/detect-data-type-in-JavaScript

Problem Description

This is an easy problem.

For all the basic data types in JavaScript, how could you write a function to detect the type of arbitrary data?

Besides basic types, you need to also handle also commonly used complex data type including Array, ArrayBuffer, Map, Set, Date and Function

The goal is not to list up all the data types but to show us how to solve the problem when we need to.

The type should be lowercase

detectType(1); // 'number'
detectType(new Map()); // 'map'
detectType([]); // 'array'
detectType(null); // 'null'

// more in judging step

Solution

const dataTypes = new Map([
  [Number, 'number'],
  [String, 'string'],
  [Boolean, 'boolean'],
  [Array, 'array'],
  [ArrayBuffer, 'arraybuffer'],
  [Date, 'date'],
  [Map, 'map'],
  [Set, 'set'],
]);

/**
 * @param {any} data
 * @return {string}
 */
function detectType(data) {
  if (typeof data !== 'object') {
    return typeof data;
  }

  if (data === null) {
    return 'null';
  }

  for (const [type, name] of dataTypes.entries()) {
    if (data instanceof type) {
      return name;
    }
  }

  return 'object';
}