Skip to content

Instantly share code, notes, and snippets.

@florian
Created April 23, 2012 18:48
Show Gist options
  • Save florian/2473010 to your computer and use it in GitHub Desktop.
Save florian/2473010 to your computer and use it in GitHub Desktop.
getting the type or constructor of a value

Usage

Getting the data type or constructor:

type("some string"); // 'string'
type(42); // 'number'
type(true); // 'boolean

Checking for a data type or constructor:

type.isNumber(42); // true
type.isNumber("string"); // false
type.isRegExp(/\d/); // true

The type function itself always returns a string. Methods of type always return a boolean.

# Some unit tests written for mocha and should.js.
# $ mocha spec.coffee --compilers coffee:coffee-script
should = require 'should'
type = require('./type.js').type
describe 'type', ->
it 'should return a string when directly called', ->
type('string').should.be.a 'string'
it 'should match booleans correctly', ->
[true, false, new Boolean].forEach (value) ->
type(value).should.equal('boolean')
type.isBoolean(value).should.be.true
it 'should match strings correctly', ->
['string', new String].forEach (value) ->
type(value).should.equal('string')
type.isString(value).should.be.true
it 'should match numbers correctly', ->
[42, new Number].forEach (value) ->
type(value).should.equal('number')
type.isNumber(value).should.be.true
it 'should match numeric values correctly', ->
type.isNumeric(value).should.be.true for value in [42, 42.5, '42', '42.5', '-42', '42e5', '0xff']
type.isNumeric(value).should.be.false for value in [Infinity]
it 'should match regular expressions correctly', ->
[/regexp/, new RegExp].forEach (value) ->
type(value).should.equal('regexp')
type.isRegExp(value).should.be.true
it 'should match functions correctly', ->
[new Function, ->].forEach (value) ->
type(value).should.equal('function')
type.isFunction(value).should.be.true
it 'should match arrays correctly', ->
[[], new Array].forEach (value) ->
type(value).should.equal('array')
type.isArray(value).should.be.true
it 'should match plain objects correctly', ->
[{}, new Object].forEach (value) ->
type(value).should.equal('object')
type.isPlainObj(value).should.be.true
(function () {
this.type = function (obj) {
return Object.prototype.toString.call(obj).match(/ (\w+)/)[1].toLowerCase();
};
type.isBoolean = function (obj) {
return type(obj) == 'boolean';
};
type.isString = function (obj) {
return type(obj) == 'string';
};
type.isNumber = function (obj) {
return type(obj) == 'number';
};
type.isNumeric = function (obj) {
return isFinite(obj) && !this.isBoolean(obj);
};
type.isRegExp = function (obj) {
return type(obj) == 'regexp';
}
type.isFunction = function (obj) {
return type(obj) == 'function';
};
type.isArray = function (obj) {
return type(obj) == 'array';
};
type.isPlainObj = function (obj) {
return obj === Object(obj);
};
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment