Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript CoffeeScrip's type function


May 09, 2021 CoffeeScript


Table of contents


CoffeeScrip's type function

Problem

You want to know the type of a function without using typeof. ( To find out why typeof isn't reliable, see http://javascript.crockford.com/remedial.html.)

Solution

Use this type function below

type = (obj) ->
    if obj == undefined or obj == null
      return String obj
    classToType = {
      '[object Boolean]': 'boolean',
      '[object Number]': 'number',
      '[object String]': 'string',
      '[object Function]': 'function',
      '[object Array]': 'array',
      '[object Date]': 'date',
      '[object RegExp]': 'regexp',
      '[object Object]': 'object'
    }
    return classToType[Object.prototype.toString.call(obj)]

Discuss

This function mimics jQuery's $.type function.

It is important to note that in some cases, you do not have to detect the type of object as long as you use duck type detection and presence operators. For example, the following line of code does not have an exception, and it pushes an element into myArray if it is indeed an array (or a class array object with a push method), otherwise do nothing.

myArray?.push? myValue